Ad

How To Use WhiteSpace: 'pre-wrap' On React

- 1 answer

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>
}
Ad

Answer

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>

Ad
source: stackoverflow.com
Ad