Trans-Component does not work with next/link`s Link component.
See original GitHub issueDescribe the bug
I’m trying to use the native next/link component inside the Trans component of react-i18next to render a text containing a link for different languages. This causes an Error: React.Children.only expected to receive a single React element child.
on the link component. It seems like the Trans
component adds something to the actual content of the link which causes this error.
Funnily enough: I also tried it with the link component of react-router-dom
and even a standard <a>
tag and with these two options everything works as expected.
Since my project relies heavily on the next/link
switching is not really an option.
Occurs in react-i18next version
node: 12.12.0
"next": "^9.3.0",
"react-i18next": "^11.0.0",
To Reproduce I tried the example from the Trans documentation:
<Trans i18nKey="userMessagesUnread" count={2}>
Hello <strong title={t('nameTitle')}>{{ name: 'Hans' }}</strong>, you have {{ count: 2 }} unread message. <Link href="/msgs">Go to messages</>
</Trans>
with the standard json coming with it:
{
"userMessagesUnread": "Hello <1><0>{{name}}</0></1>, you have <3>{{count}}</3> unread message. <5>Go to messages</5>",
"nameTitle": "Whatever title should be on the strong element"
}
Issue Analytics
- State:
- Created 3 years ago
- Reactions:3
- Comments:8 (1 by maintainers)
Thanks for the gentle nudge in the right direction. It seems like the next/link requires a non-string descendant. So everything can be fed to the Link component except for pure strings, since it expects any kind of component or component like structure like an
<a>-tag
.I solved it with a intermediate component:
Which is then used like in the documentation example:
I guess this issue can then be closed. Finally 😄
Based on @ClemensGrunewald 's solution above, this time with TypeScript and Trans alternative usage:
First, define
LinkText
once for all in your app:In your
translations.json
file:Important note: the name
link
is reserved! Thus the unnaturallnk
or whatever you prefer.In your code: