0

I have text(paragraphs) stored in my database that includes line breaks. When I do a GET request to the database, the information comes back as an object. The portion with the text turns into one large clumped up paragraph. Does anyone know how I can maintain the line breaks and text format when passing the text around?

Justin C.
  • 109
  • 1
  • 9
  • 1
    you can pass data from api as array of paragraphs and use \n symbol to have new line after rendering each element of array – igorves Jan 08 '19 at 19:35

1 Answers1

1

You can split the line breaks into an array and the use the map function to show and style them the way you want. Here's a simple solution that can be further modified according to your needs:

const myObj = {
  text: 'Very large text\nLine1\nLine2\nLine3'
};
const text = myObj.text.split('\n');

class App extends React.Component {
  render() {
    return ( 
        <div>
        {text.map((t, i) => <div key={i}>{t}</div>)}
        </div>
      );
  }
}

ReactDOM.render( < App / > ,
  document.getElementById('root')
);
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script><div id="root" />
Hamed
  • 1,351
  • 9
  • 23
  • Hi Hamed. The '\n' line breaks aren't currently being stored in the database, but it shows the line breaks? Basically I have a large textarea input on my front end. The user can paste in text (like the body of an article) and save it. It will be saved in the database with all of the paragraph spacing. But there isn't actual '\n' (or at least it doesn't show?). So when I pull from the database, it comes back to the front end as one large paragraph. Would I need to do something to the user's pasted text so it has the line breaks and such? Or is there a way I can store whatever is pasted as html? – Justin C. Jan 08 '19 at 22:31
  • 1
    If the user actually press enter somewhere in the textarea, then the linebreak will be stored once you save your data in the DB. Otherwise it will be considered as a large single paragraph. Textarea is incapable of storing HTML content so it removes all formatting. You can replace you textarea with Quill (https://quilljs.com) and it allows you to save and load HTML content (with some limitation). Also you can refer to this discussion about line breaks in textarea: https://stackoverflow.com/questions/863779/javascript-how-to-add-line-breaks-to-an-html-textarea – Hamed Jan 09 '19 at 05:43