The <Trans> Component (when and how to use it)
The <Trans> component should be used when you have react/HTML nodes integrated within a sentence.
Examples of where the <Trans>
component is needed:
<link>
<abbr>
<strong>
<br>
Where the <Trans>
component is not needed:
A whole word or sentence is wrapped inside a react/HTML node.
Conventions
HTML values are kept out of the locale files
HTML values within translation key text can decrease readability.
Hard coded text is not used outside the locale files
Using hard coded text within the
<Trans>
component means the text has to be maintained in two places. Therefore, we should avoid using hard coded text outside the locale JSON files for easy maintenance.
Links used in the home page are kept inside the homeConfig.ts file
This is for easy alteration if links are changed
Adding a link with the <Trans> component
Our plain sentence in our JSON file, without any markup:
hello_msg: "Hello amazing world."
We are going to add a link on the word ‘amazing’ to www.google.com.
In the file where we want to render our sentence, we will first add the <Trans>
<Trans>
We will then state the i18nKey
as a prop. This is the key we associate with our sentence in the JSON file.
<Trans i18nKey="hello_msg" />
Our sentence will now be rendered, but without any link yet.
To render the sentence with a link, the components
prop is added.
Now back in our JSON file, we edit our key where we want our link to be.
Adding a link without the <Trans> component
A link can be added to a whole sentence without the <Trans>
component.
Adding formatting to a word in a sentence
Our key in the JSON file:
Now say we want to make the word “local code” and “local meaning” bold.
To do this we would use the
<Trans>
component again in the same way we did with links.We use
i18nkey
as a prop to state the key.We then use the
components
prop to reference the HTML value.Any name can be used here to represent the
<strong>
HTML.In this case, I have used the word ‘bold’ as it makes it clear what the HTML represents.
Then, in the JSON file, the key is altered to include the HTML.
Adding line breaks in text
Our key in the JSON file:
Now say we want to break up the text to make it more readable.
To do this we would use the
<Trans>
component again in the same way we did with links.We use
i18nkey
as a prop to state the key.We then use the
components
prop to reference the HTML value.
Any name can be used here to represent the
<br>
HTML.In this case, I have used the word ‘break’ as it makes it clear what the HTML represents.
Then, in the JSON file, the key is altered to include the HTML.
Operated as a Community Resource by the Open Library Foundation