Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Render newline character in React

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

But that did not work. Thanks for reading!

>Solution :

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.

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading