How to break line in React i18n json translations

Mar 16, 2022

My new co-worker Borgia (check out his agency #notsponsored) convinced me to fix the text on the top of the homepage. Do you think he was right? Of course, you'd think you can rely on the infamous a<brrrr />. I mean <br /> html tag if it fits your needs. But what if you can't? What if your text comes from an API response or, even worse, a JSON translation file 🫢???

Screenshot of text needing a break line in json translations (ex.: React i18n)

This is rather common in React and my exact usecase. This made me find out about a nice little CSS trick to control this! And I hate to say that Borgia ahem #notsponsored https:/.. was right. Placement plays a nice role in readability and the overall aesthetic. So, let's raise our pinky as we do this!

Break line with \n and CSS

My first try? Adding \n in the translation string.

"...": "...",
"hero_2": "\nJe développe, j'apprends et j'améliore — spécialisé Front-end"

Still no change. The \n isn't visible, but it didn't add a linebreak; so here's where the CSS comes in. We need to add white-space: pre-line to the element that contains the text in question.

h1 {
white-space: pre-line;

A preview, just in case :

const { t } = useI18next("index");

Using TailwindCSS? There's a class: whitespace-pre-line

Break line with

<br />

Not much to say to that, is there?

Published on March 16, 2022

Written by Vladislav Kim