DEV Community

Yuya Hirano
Yuya Hirano

Posted on

How to display line breaks in React for the "\n" newline character.

In React, displaying the newline character "\n" as a line break in HTML can be tricky as it won't be interpreted as a newline character. However, React provides a way to display line breaks for string with "\n" characters in HTML.
For example, to display a newline code contained in a value received from the API, etc. as a newline, one function must be interspersed.

When dealing with strings that contain newline characters (\n) in React, you may want to convert them to
tags to display line breaks in the UI. However, simply replacing \n with
in the string won't work as expected in JSX, since the string
will be rendered as text rather than as a line break.

// const text = "Apple\nOrange\nBanaa";
const element = ({ text }) => {
  const newlineText = text.replace(/\n/g, '<br />');
  return <div>{newlineText}</div>;
}
Enter fullscreen mode Exit fullscreen mode

The results is here:

Apple<br />Orange<br />Banana
Enter fullscreen mode Exit fullscreen mode

Here is an example of how to display line breaks in React for the "\n" newline character:

import React from 'react';

function TextWithLineBreaks(props) {
  const textWithBreaks = props.text.split('\n').map((text, index) => (
    <React.Fragment key={index}>
      {text}
      <br />
    </React.Fragment>
  ));

  return <div>{textWithBreaks}</div>;
}

export default TextWithLineBreaks;
Enter fullscreen mode Exit fullscreen mode

In this example, the TextWithLineBreaks component splits the input text string into an array of substrings using the split() method with "\n" as the separator. It then maps over each substring, adding a
element after each substring to represent the newline.

The React.Fragment component is used to group multiple elements returned from the map() function into a single element.

Here is how the TextWithLineBreaks component can be used to display text with line breaks:

import React from 'react';
import TextWithLineBreaks from './TextWithLineBreaks';

function App() {
  return (
    <div>
      <TextWithLineBreaks text="Hello\nWorld" />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

In this example, the TextWithLineBreaks component is passed the string "Hello\nWorld" and will display it with a line break between "Hello" and "World".

Using this method, you can easily display text with line breaks in React for the "\n" newline character.

The sample code in this article is partially modified from the one generated by openAI.

Top comments (3)

Collapse
 
devdufutur profile image
Rudy Nappée • Edited

Or just put the text in a < pre > tag 😉
(and don't trust blindly openAI)

Collapse
 
lionelrowe profile image
lionel-rowe

white-space: pre-wrap is better, as you probably don't want to turn off line wrap at the same time.

Collapse
 
devdufutur profile image
Rudy Nappée

Nice!