3

I have a string that contains a new line character. For example:

const myString = `hello\nstring`

I am then trying to dispaly this string in a functional component, which is wrapped around a p tag. For example:

export default function App() {
  const testString = "hi\nString";
  return (
    <div className="App">
      <p>{testString}</p>
    </div>
  );
}

For some reason, the p tag simply displays "hello string" on one line when I'd like for it to be displayed across two lines. Is there a way that I can stop the p tag from removing the new-line character from within the string?

The following Code Sandbox contains the executable example: https://codesandbox.io/s/unruffled-allen-ehrsd8?file=/src/App.js

Adam
  • 2,384
  • 7
  • 29
  • 66
  • 1
    This isn't related to React. HTML layout ignores linebreaks and collapses whitespace, so you can format your HTML code without messing up the layout. If you want a line break you need to convert the `\n` to a `
    ` ,or wrap the text in a `
    `.
    – Daniel Beck Mar 28 '22 at 12:10
  • Thank you for the suggestion. I've tried to wrap the text in both `
    ` or `
    `, but those are then inserted as literal strings.
    – Adam Mar 28 '22 at 12:28
  • _That_ part is related to react. https://stackoverflow.com/questions/19266197/reactjs-convert-html-string-to-jsx – Daniel Beck Mar 28 '22 at 12:29

3 Answers3

4

I think this is because new lines and white spaces are collapsed in browser by default. You do not need any JavaScript for this, just add following line in your stylesheet -

p {
  white-space: pre-wrap;
}
Zakariya Qureshi
  • 2,084
  • 2
  • 8
  • 9
  • 1
    Thank you! I have accepted this answer as it's more elegant in my opinion than the other working solution. – Adam Mar 28 '22 at 12:39
1

Did you use <br/> code to break the line.? Please check code as given below-

export default function App() {
  const testString = "hi<br/>String";
  return (
    <div className="App">
      <p>{testString}</p>
    </div>
  );
}
JoSSte
  • 2,953
  • 6
  • 34
  • 54
Varun Kaklia
  • 366
  • 4
  • 9
1

You can use .split method whenever \n is found inside your code to enter new line

  function NewlineText(props) {
  const text = props.text;
  const newText = text.split('\n').map(str => <p>{str}</p>);
  
  return newText;
}

export default function App() {
  const testString = `hi\nString`;
 return (
    <div className="App">
<p><NewlineText text={testString} /></p>
    </div>
  );
}

This site might clear your any remaining doubts.

NL_Dev
  • 111
  • 6