Reputation: 477
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.
Upvotes: 8
Views: 5955
Reputation: 295
The answer provided by @Sagiv b.g is correct.
white-space: pre-line
is the key here.
Please find CodePen Link for your example
JSX:
let exampleText = `This should be line 1
And this should be line 2
Maybe this will be line 3?
or maybe this?`;
var aboutItems = {
headerClass: "aboutSection content",
header: "About Me",
subtitle: "Developer. Entrepreneur. Engineer.",
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="multiline">{this.props.items.text}</p>
</div>
);
}
}
ReactDOM.render(
<Site />,
document.getElementById("root")
);
CSS:
.multiline {
white-space: pre-line;
}
Upvotes: 3
Reputation: 31024
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>
Upvotes: 16