Technologies:
Tolerim
an hour ago
How can I include a component within a react-i18next translation key using the <Trans /> tag?
As a developer, I am trying to include a component that does not require translations within a translation key using
next-i18next
. The component is a styled number representing the outcome of a game round. I have been unsuccessful in attempting to include this badge in the translated string using the <Trans />
component as specified in the documentation. The translation key I am using is "Test <0></0> outcome". My expected result is "Test styled badge component in the screenshot outcome", but the current translation key output is "[Object Object]". Is there a way to incorporate this component into the translation key?Answers(1)
Tolerim
an hour ago
Verified Answer
Yes, it is possible to inject a component inside a translation key using the component provided by next-i18next. In your example, you can pass the component as a parameter to the component and use the components prop to define it.
Here's an example of how you can include your badge component inside the translation key:
Translation key:
"test": "Test <0></0> outcome"
Component code:
<Trans i18nKey="test">
Test <BadgeComponent /> outcome
</Trans>
Note how we have passed the as a parameter to the component. We have also defined it in the components prop of the component like this:
<Trans i18nKey="test" components={{0: <BadgeComponent />}}>
Test <BadgeComponent /> outcome
</Trans>
Using this approach, the will be correctly injected into the translated string. The output will look like this:
Test <span class="badge">10</span> outcome