Pass dynamic value into react-i18next useTranslate
Asked Answered
L

2

7

So I have a value I am receiving from an endpoint and I'd like to pass it into my translate command.

So this is what I have currently: ${t('translation:user.form.placeholder')}

And I'd like to be able to do something like this: ${t('translation:user.form.${placeholder}')}

Is there a way to do this? I'm happy to provide more clarity to the question if needed. Any help would be appreciated.

Lifeordeath answered 17/3, 2022 at 1:32 Comment(1)
Did you find a solution to that? Would like to know.Modestomodesty
S
13

Looking at the question I am assuming you want to interpolate a string with a dynamic value. For instance

{
    "translation:user.form": "Some text with {{dynamicValue}}"
}

This dynamicValue can be replaced with second param options which a string or TOptions<StringMap>.

    const { t } = useTranslation();
    ...
    t('translation:user.form', {dynamicValue: 'Some value or variable'})

Here is the doc for interpolation https://www.i18next.com/translation-function/interpolation

Sandglass answered 6/5, 2022 at 15:26 Comment(1)
is there a way to make the variable clickable?Zumwalt
K
0

To pass a variable and make it clickable link there is a i18next component provided by the library. You can use links inside of it and pass variables easily.

https://react.i18next.com/latest/trans-component

Following example is from documentation and works pretty well.

import { Trans } from 'react-i18next';
function MyComponent({ person, messages }) {`
  const { name } = person;`  
  const count = messages.length;
return(
    <Trans i18nKey="userMessagesUnread" count={count}>
      Hello <strong title={t('nameTitle')}>{{name}}</strong>, you have {{count}} unread message. <Link to="/msgs">Go to messages</Link>.
    </Trans>
)
Koby answered 10/8, 2023 at 6:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.