DEV Community

Cover image for Handling and Displaying Strings with Line Breaks in React
Atsushi Suzuki
Atsushi Suzuki

Posted on

1

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

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay