Let’s see how to add new line when working with strings in React.

Three ways to create new line in React

JavaScript methods

Let’s say you have a long string with newline characters. Pieces of text between newline characters need to be rendered on a new line.

First you need to create an array of strings separated by ‘\n’. Every item in the array will be a piece of text between newline characters in the combined string.

To do this, you need to call split() method. When applied to a string, this method searches for a specific symbol and creates an array of sub-strings separated by that symbol – in this case, newline character.

const text = "Lorem ipsum \n dolor sit \n amet";

When applied to the text string, split() will create an array of sub-strings. You only need to specify the symbol that separates pieces of string.

Once you have the array, you can use map() to create a <p> element for every piece of string in the array.

By default, <p> elements (paragraphs) start on a new line. So you will create a line break in the string in React.

Here’s a final code, and live preview to see new lines for every newline character in React.

<p> tags also add space between lines. So they also improve style.

This approach allows you to add new lines in React even if pieces of string are separated by characters other than the newline character ‘\n’. For example, if you want to add new line between strings separated by a comma, you only need to specify that symbol as argument to the split() method.

CSS Rules

The simplest way to create new lines between strings is to add a CSS rule, and have newline character to break up the string.

Make sure to add this CSS rule to the container that holds the text, not the <p> (or other) element itself.

In this live demo, we have set white-space CSS property to pre-wrap. As you can see, it adds new line in React.

div {

  font-family: sans-serif;

  text-align: center;

  white-space: pre-wrap;

}

<pre> tag

The <pre> tag allows you to define a preformatted HTML text.

Wrap a string that contains newline characters with <pre> tags. If a string doesn’t have any, add newline characters yourself to add new line in React.

function App() {
  const text = "Lorem ipsum \n dolor sit \n amet";
  return (
    <div className="App">
      <pre>{text}</pre>
    </div>
  );
}

However, the text is not formatted in any way. This is the feature of the <pre> tag.

UX