Handling and Displaying Strings with Line Breaks in React

suzuki0430

Atsushi Suzuki

Posted on May 5, 2023

Handling and Displaying Strings with Line Breaks in React

When an error message containing line break code \n is returned from an API access, the line breaks were not reflected when the message was output as is. I thought that converting \n to <br> would solve the problem, but <br> was just output as a plain text string. As it took some time to resolve the issue, I am leaving a note for reference.

Issue

Line breaks are not reflected when outputting a message containing line break codes.

const Body = () => {
  const body =
    'Bulbasaur\nCharmander\nSquirtle\nPikachu';

  return (
    <div>
      {body}
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Image description

Solution 1: Splitting a String with Line Breaks into Components

In this solution, we split the original string by line breaks and create a component with <br> tags added to each element. This allows us to properly display the string with line breaks reflected.

const Body = () => {
  const body =
    'Bulbasaur\nCharmander\nSquirtle\nPikachu';

  return (
    <div>
      <MultiLineBody body={body} />
    </div>
  );
};

const MultiLineBody = ({ body }: { body: string }) => {
  const texts = body.split('\n').map((item, index) => {
    return (
      <React.Fragment key={index}>
        {item}
        <br />
      </React.Fragment>
    );
  });
  return <div>{texts}</div>;
};
Enter fullscreen mode Exit fullscreen mode

Image description

Solution 2: Using CSS to reflect line breaks

In this solution, we set the CSS property whiteSpace to pre-line to reflect the line break codes.

const Body = () => {
  const body =
    'Bulbasaur\nCharmander\nSquirtle\nPikachu';

  return (
    <div style={{ whiteSpace: 'pre-line' }}>
      {body}
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode
πŸ’– πŸ’ͺ πŸ™… 🚩
suzuki0430
Atsushi Suzuki

Posted on May 5, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related