Home > Blockchain >  Render newline character in React
Render newline character in React

Time:09-20

let arr = [{text: "1 x Coffee for 3,4 Euro \n\n3 x Coffee for 3,5 Euro"}]

I would like to parse the newline character( \n) so that every Coffee is displayed on its own line. Like:

'1 x Coffee for 3,4 Euro'
'3 x Coffee for 3,5 Euro'

I tried:

 function FormatBody() {
        return <> {`${arr[0].text.replace(/\n/g, "<br />")}`} </>
      }

But that did not work. Thanks for reading!

CodePudding user response:

Instead of adding <br> elements you could split the text on the line return, and then map over that array and wrap each sentence in a paragraph element. This is also slightly more useful in case you need to style the parapraphs differently which you wouldn't be able to do with text separated by <br> elements.

function Example({ data }) {

  function formatBody(text) {
    return text.split(/\n /).map(p => <p>{p}</p>);
  }

  return (
    <div>
      {formatBody(data[0].text)}
    </div>
  );

}

const data = [{text: "1 x Coffee for 3,4 Euro  \n\n3 x Coffee for 3,5 Euro"}]

ReactDOM.render(
  <Example data={data} />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

  • Related