Reputation: 46372
Instead of a translation like in this basic example
{
"key": "{{what}} is {{how}}"
}
i18next.t('key', { what: 'i18next', how: 'great' });
// -> "i18next is great"
I need a result like
<i>i18next</i> is <i>great</i>
as a react node to be rendered as
i18next is great
I could generate the string "<i>i18next</i> is <i>great</i>"
and use it with dangerouslySetInnerHTML
, but that's ugly and dangerous.
I could split the key like
{
"key1": "{{what}}",
"key2": "is",
"key3": "{{how}},
}
and use
const params = { what: 'i18next', how: 'great' };
return <>
<i>{i18next.t('key1', params)}</i>
{i18next.t('key2', params);}
<i>{i18next.t('key3', params)}</i>
<>
which is safe, but even uglier. Moreover, in general, it requires to split every key with n
arguments into 2*n+1
parts, which are related by nothing but a naming convention.
We'd like to apply some formatting (not necessarily <i>
; this was just an example) to all parameters, so we need a better solution. I'm not looking for a library, i18next was just an example. Any idea?
Upvotes: 0
Views: 61
Reputation: 4373
You could try to use the Trans Component
A key looking like
key: "<0>{{what}}</0> is <2>{{how}}</2>"
can be used with
// const what = "Pizza";
// const how = "great";
<Trans i18nKey="key">
<strong>{{ what }}</strong> is <i>{{ how }}</i>
</Trans>
and will produce: Pizza is great
Here is a playground codesandbox
Hope it helps!
Other libraries do it differently - ex: react-intl can handle tags in the lang definitions - this example
Upvotes: 1