How to preserve space character between replacement tags in i18next translation string
Asked Answered
S

2

5

I am using v10 of react-i18next and the latest Trans component to have a translation string with a portion of the sentence bolded.

In the HTML I can insert a &nbsp; to ensure there is a space between the <strong> block and the rest of the sentence but it gets stripped out in the translation string.

JSX file:

<Trans i18nKey="free_trial_enabled">
  <strong>30 Day Free Trial enabled</strong>&nbsp;for all users
</Trans>

JSON translation key/value file:

"free_trial_enabled": "<0>30 Day Free Trial enabled</0> for all users",

Output HTML: <strong>30 Day Free Trial enabled</strong> for all users

Which looks like: '30 Day Free Trial enabledfor all users'

How can I preserve the &nbsp; in the translation string so the space after the strong block will be there?

Stagger answered 10/4, 2019 at 17:38 Comment(1)
It works for me: codesandbox.io/s/qo18n4vjj, maybe you have some css that removes whitespace?Ailis
S
7

Thanks @felixmosh! white-space: pre-wrap; fixed the issue.

Stagger answered 11/4, 2019 at 18:13 Comment(0)
H
3

I am sharing my knowledge here. Using

white-space: pre-wrap;

Works all fine. however, in my case, I was not able to use it due to the structure of my text. I needed some text with some anchor in between. In order to get it work, I have to do the following:

  "my_string": "<p><Link>Some anchor texr</Link> followed by normal text.</p>",

Then, I substitute my translatable string as follows:

<Trans
          i18nKey="my_string"
          components={{
            Link: <a target="_blank" rel="noopener noreferrer" href={"https://some_url"}/>
          }}
        />

This way works also fine in terms of adding white spaces between anchor text and normal text.

I hope this will be helpful to others as in my case, almost all of scenarios that I end up having to use i18next components are because of needing to show anchors.

Also, in case you need to be able to style your paragraph, you can make a change like this:

  "my_string": "<Paragraph><Link>Some anchor texr</Link> followed by normal text.</Paragraph>",

Then, in your components declaration:

<Trans
          i18nKey="my_string"
          components={{
            Paragraph: <p className={"my-auto"}/>,
            Link: <a target="_blank" rel="noopener noreferrer" href={"https://some_url"}/>
          }}
        />
Heteromerous answered 9/12, 2022 at 16:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.