How to create a new line in JSX and Reactjs

When creating components in React.js there are situations where newlines are required inside the render function. This can be due to a whole host of reasons including:

  • Formatting text
  • Creating new paragraphs
  • Creating a space between each element mapped in a loop

So, how exactly can you create a new line in JSX? Well, there are multiple ways to achieve this:

  • Using CSS’s white-spaceproperty
  • Using .split() with '\n'
  • Using <br>with dangerouslySetInnerHTML (not recommended)

Let’s say we have a string value with a \n like so:

const text = 'Tommy Vercetti \n Carl Johnson'

Ideally, once the JSX has rendered, we want these two names to be on separate lines:

Tommy Vercetti
Carl Johnson

Inside our render function we want to loop through the string:

let newText = text.split('\n').map(i => {
    return <p>{i}</p>
});

Using CSS white space

We could render the text like so:

render() {
 <p>{text}</p>
}

And apply the white space property:

div {
  white-space: pre-wrap;
} 

Using Split

We can split the string by the backspace (\n). This converts the string to an array with two values. 

let newText = text.split ('\n').map ((item, i) => <p key={i}>{item}</p>);

From here, we can .map() through the array and put each element inside a paragraph. Since paragraph use display:block, each element will be on its own line which accurately represents the backspace in the string.

Using dangerouslySetInnerHtml

This approach is not to be recommended unless you have sanitized your markup. Otherwise you risk cross-site scripting attacks.

In your React component’s render function:

 render() {
    return (
      <div contentEditable='true' dangerouslySetInnerHTML={{ __html: text }}></div>
    );
  }

This will replace the \n in the string with a <br>to create a line break. Use with caution!

Hopefully, this helped you to create a new line where needed in your web application.

If you are looking to get your dream software engineering position I’d recommend subscribing to Mosh’s all-access membership to improve your skills as a React developer.

Proudly published with Gatsby