Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting line breaks with string literals in html elements using React

I have a problem I am trying to solve. I saw some other questions but they didn't have the same issue as me. This is what I am currently am trying to do.

Text.js

export let exampleText = `This should be line 1
And this should be line 2
\n Maybe this will be line 2?
\\n or maybe this?`

app.jsx

var aboutItems = {
    headerClass: "aboutSection content",
    header: "About Me",
    subtitle: "Developer. Entrepreneur. Engineer.",
    text: Text.exampleText
}
class Site extends React.Component {
    render() {
        return (
            <div>
               <Section items = {aboutItems}/>
            </div>

        );
    }
}
class Section extends React.Component {
    render() {
        return (
            <div className = {this.props.items.headerClass}>
                <h1>{this.props.items.header}</h1>
                <h2>{this.props.items.subtitle}</h2>
                <p className="multi-line">{this.props.items.text}</p>
            </div>
        );
    }
}
ReactDOM.render(
    <Site />,
    document.getElementById("root")
); 

However when the text comes it shows as this in the html:

This should be line 1 And this should be line 2 Maybe this will be line 2? \n or maybe this?

I tried adding a css style in class multi-line such as white-space: pre and though this does add the multi line it doesn't remove other whitespace so using styling such as padding or margins no longer worked.

What is the work around to this, or a better practice?

Thanks in advance.

like image 819
ZarifS Avatar asked Dec 24 '22 11:12

ZarifS


1 Answers

You should use the css rule of

white-space: pre-line;

With combination of string literals or \n

Here is a running example with string literals:

const App = () => (
  <div className="line-break">
    {`this is line 1 
    
     
     
     and this is line 2`
    }
  </div>
);

ReactDOM.render(<App />, document.getElementById('root'));
.line-break {
  white-space: pre-line;
}
<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 168
Sagiv b.g Avatar answered Feb 15 '23 10:02

Sagiv b.g