Search code examples
reactjsi18nextreact-i18next

Dynamic content inside Trans Component i18next


I have a list of translated keys and react component content. e.g :

    list = [{ translation: "Hello <1>World</1>", content: "Hello <a href='#'>World</a>" },
{ translation: "A <1>B</1>", content: "A <a href='#'>B</a>" }]

The idea is to show a translated data from the list using the "translation" and the structure of "content" with Trans Component of i18next-react with a map function.

{list.map((item) => (
<Trans i18nKey={item.translation}>
    {item.content}
</Trans>))}

Unfortunately, this doesn't seem to work at all, the outcome is only the translated string, without the structure that should came by the React Component content.

Any idea how to work around this?


Solution

  • Just in case anyone will try to do this in the future: The way to do so is to use components props as Jamuhl mentioned. And to pass there an array with the HTML elements of the "item.content". The way to get the array of HTML elements from a string as we have on "item.content" is by using ReactHtmlParser that parse that string into an HTML elements array! ReactHtmlParser can be cloned from here: https://www.npmjs.com/package/react-html-parser