最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Pass dynamic value into react-i18next useTranslate - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Mar 17, 2022 at 1:32 IreIre 851 gold badge1 silver badge4 bronze badges 1
  • Did you find a solution to that? Would like to know. – Kay_S Commented May 13, 2022 at 17:33
Add a comment  | 

2 Answers 2

Reset to default 15

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

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>
)
发布评论

评论列表(0)

  1. 暂无评论