i18next bold text in the middle of a translation
Splitting the sentence will defeat the purpose of having translations, what if another language requires the split parts in a different order?
Also I'm not fond of the Trans component since you need to maintain the translation in both the default JSON and in the React code.
I suggest using embedded HTML, but be careful if you have a user input in the translation since it should be manually escaped.
In your case since you don't have any user inputs just go with:
JSON:
{
"common": {
"greeting": "We will see you at <b>NEW YORK</b> in the morning!"
}
}
React:
<div dangerouslySetInnerHTML={{__html: translate("common.greeting")}} />
Thanks to @adrai for noting the answer in a comment, thought i'd type it out here for future visitors;
Read the full docs at https://react.i18next.com/latest/trans-component
You can use the <Trans>
component from react-i18next
import { Trans } from 'react-i18next'
I'm assuming that the 'NEW YORK' text should be dynamic (easily replaceable), if not you don't need the values
part.
<Trans i18nkey='common.greeting' values={{ city: 'NEW YORK' }}>
We will see you at <strong>NEW YORK</strong> in the morning!
</Trans>
Then, in the locale JSON file you can use <N>
as a placeholder for the Nth JSX tag used inside the <Trans>
tag and {{key}}
for any dynamic value (like city in this case)
{
"common": {
"greeting": "We will see you at <1>{{city}}</1> in the morning!"
}
}
The text inside the <Trans>
component is only used as a fallback if no translation is found, but the <strong>
tag will replace the <1>
placeholder.