NextJS Intl: Mixed-up markup translations

NextJS Intl: Mixed-up markup translations

Today will talk about how to handle complex translations with HTML elements in the middle with NextJS Intl .

Prerequisites

Would assume you have heard already about NextJS Intl or a similar library. If not, take a look at the link added previously.

The problem

Output:

<span>page <strong>1</strong> of <strong>10</strong><span>

how would you end translating this in the JSON files, breaking it into separate strings properties?

"paginationTitle": "page"
"paginationOf": "of"

and then on code like ?:

<span>{t('paginationTitle')} <strong>{currentPage}</strong> {t('paginationOf')} <strong>{{total}}</strong><span>

Not practical!!

A solution

NextJS Intl considers this, but offers a component fashion way on how to interpolate with HTML tags, first from component, we pass the values as normal, but also as part of the object values we create a function that returns a JSX element:

{t('paginationIndicator', {
    currentPage: currentPage,
    total: total,
    heavyText: (children) => (
    <strong>
        {children}
    </strong>
    ),
})}

Then is when we can use that, in order to give some format and special styling at some point to the paginationIndicator string:

"paginationIndicator": "page <heavyText>{currentPage}</heavyText> of <heavyText>{total}</heavyText>"

NOTE: just consider if you don't need to pass any children, you still need to open and close the element in the JSON file

References

github.com/amannn/next-intl/blob/main/docs/..