Ad

React: Inserting A Line Break In Localised Text

- 1 answer

I'm getting localised text from a JSON file and displaying it to the page, my problem is that the \n and <br> notations are being ignored.

I've made a code sandbox here to show how the text doesn't get put on more than one line.

import * as React from "react";
import { render } from "react-dom";

const App: React.FC = props => {

  const Translations: {
    [key: string]: {
      fname: string;
    };
  } = {
    en: {
      fname: "I want to insert a break in this line of text so it shows on two lines \n doesnt work and <br> does either",
    },
    cn: {
      fname: "我想在这一行文本中插入一个中断,以便在两行中显示\ n不起作用,而<br>可以",
    }
  };

  const txt = Translations["en"];


  return (
    <div className="App">
      <p>{txt.fname}</p>
    </div>
  );
};

const rootElement = document.getElementById("root");
render(<App />, rootElement);

Ad

Answer

In order to respect \n, you can add a style of white-space: pre-line or white-space: pre-wrap.

In React, it would look like this:

return (
    <div className="App">
      <p style={{ whiteSpace: "pre-line" }}>{txt.fname}</p>
    </div>
  );

Here is a forked sandbox.

Ad
source: stackoverflow.com
Ad