How to display line breaks in React for the "\n" newline character.
Yuya Hirano
Posted on March 12, 2023
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>;
}
The results is here:
Apple<br />Orange<br />Banana
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;
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;
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.
Posted on March 12, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.