user0101
user0101

Reputation: 1527

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>"

Upvotes: 3

Views: 6618

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 282040

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

Upvotes: 4

chandan_kr_jha
chandan_kr_jha

Reputation: 557

Change to prop to href prop. You are using html anchor tag not react router dom Link.

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

Upvotes: 0

Related Questions