Skip to content
All writing

How to break line in React i18n JSON translations

Two ways to add a line break to text from a react-i18next JSON file — \n with white-space pre-line, or <br/> with the Trans component.

#snippetsreacti18ncssjavascript

A co-worker (Borgia) convinced me the homepage headline needed a line break. He was right, which is annoying.

In plain JSX you'd drop a <br /> and move on. But the text lives in a JSON translation file, and a <br /> inside a string renders as literal text.

Text that needs a line break inside a JSON translation

Option 1: \n and white-space: pre-line

Put \n where the break goes:

{
	"hero": "Je développe, j'apprends et j'améliore\nSpécialisé front-end"
}

On its own, nothing happens. HTML collapses newlines into a space. Tell the element to keep them:

h1 {
	white-space: pre-line;
}
const { t } = useTranslation();

<h1>{t("hero")}</h1>;

pre-line keeps newlines but still collapses extra spaces, so your indentation doesn't leak into the layout. Tailwind has it as whitespace-pre-line.

Best for: plain text, and when translators shouldn't be touching markup.

Option 2: <br/> with <Trans>

react-i18next keeps a few basic HTML tags by default (br, strong, i, p) when you render through the Trans component:

{
	"hero": "Je développe, j'apprends et j'améliore<br/>Spécialisé front-end"
}
import { Trans } from "react-i18next";

<h1>
	<Trans i18nKey="hero" />
</h1>;

No CSS needed. t() still prints the tag as text, so this only works through Trans.

Best for: strings that already need bold or links, since you're in Trans anyway.

Skip dangerouslySetInnerHTML. A translation file is not a place to run HTML.

Get new posts by email

New writing in your inbox. Unsubscribe anytime.