Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-i18next - HTML <a> anchor href preservation

I am forced to use the following key:

"key": "Some Text <u><a href=https://www.example.com/>Read more</a></u>"

Is it possible to use the above in React-i18next's <Trans> component, so the href attr is used? Here's what I have so far:

i18next config:

.init({
  react: {
    transSupportBasicHtmlNodes: true,
    transKeepBasicHtmlNodesFor: ['u', 'a']
  }
})

component:

<Trans i18nKey="key">
 Text <u><a to='link'>link</a></u>
</Trans>

or

<Trans i18nKey="key">
 Text <u><a to={t('link')}>link</a></u>
</Trans>

The output is missing href attribute on anchor tag:

"Some Text <u><a>Read more</a></u>"
like image 574
user0101 Avatar asked Aug 08 '26 18:08

user0101


1 Answers

You would need to use interpolation while defining the key value because transKeepBasicHtmlNodesFor doesn't preserve the attributes.

Check this link for more details

transKeepBasicHtmlNodesFor allows elements not having additional attributes like className and only no children (void) or one text child:

  • <br/>
  • <strong>bold</strong>
  • <p>some paragraph</p>

but not:

  • <i className="icon-gear" /> // no attributes allowed
  • <strong title="something">bold something</strong> // no attr
  • <bold>bold<i>italic</i></b> // no inner elements - only strings!

For your case you would use the key

"key": "Some Text <1><0>Read more</0></1>"

and use it with Trans like

<Trans i18nKey="key">
 Text <u><a href="href=https://www.example.com/">link</a></u>
</Trans>

Keep in mind to use href and not to attribute on anchor tag

Check How to get the correct translation string? for writing a correct translation string

like image 65
Shubham Khatri Avatar answered Aug 11 '26 06:08

Shubham Khatri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!