Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use whiteSpace: 'pre-wrap' on React

How can I use the style whiteSpace: 'pre-wrap' on React

I have a div that need to render the text using the format with spaces

render() {
   <div style={{whiteSpace: 'pre-wrap'}}
      keep formatting

      keep spaces
   </div>
}
like image 884
Sibelius Seraphini Avatar asked Apr 02 '16 18:04

Sibelius Seraphini


People also ask

What does white space pre-wrap do?

Perhaps you like how pre honors white space and breaks, but you need the text to wrap instead of potentially break out of its parent container. That's what white-space: pre-wrap; is for: Finally, white-space: pre-line; will break lines where they break in code, but extra white space is still stripped.

What does white space pre line mean?

pre. Sequences of white space are preserved. Lines are only broken at newline characters in the source and at <br> elements. pre-wrap. Sequences of white space are preserved.

How do you add a white space in CSS?

In CSS, you can use either the margin or padding properties to add space around elements. Additionally, the text-indent property adds space to the front of the text, such as for indenting paragraphs.


1 Answers

JSX collapses whitespaces, in this case you can use dangerouslySetInnerHTML like so

var Component = React.createClass({
  content() {
    const text = `
      keep formatting

      keep spaces
   `;

    return { __html: text };
  },

  render: function() {
    return <div 
      style={{ whiteSpace: 'pre-wrap' }} 
      dangerouslySetInnerHTML={ this.content() } 
    />
  }
});

Note: For new versions of React/JSX, there is no need to use dangerouslySetInnerHTML

const App = () => (
  <div style={{ whiteSpace: 'pre-wrap' }}>
    {`
      keep formatting

      keep spaces


      keep spaces
   `}
  </div>
);

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
like image 68
Oleksandr T. Avatar answered Sep 23 '22 19:09

Oleksandr T.