I want to pass text to my react component using props. The important thing is I need the new line symbol ("\n") to work.
My example is very simple:
class UnderlinedText extends React.Component {
render() {
const text = 'Hello\n this is a test'; // this works
// const text = this.props.text; this does NOT work
return (
<div className="textContainer">{text}</div>
);
}
}
ReactDOM.render(
<UnderlinedText />,
document.getElementById("root")
);
.textContainer {
white-space: pre-line;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Using the hardcoded text above everything works as it should (even in debug I see that the string spans in multiple lines). But using it via props like so:
class UnderlinedText extends React.Component {
render() {
const text = this.props.text;
return (
<div className="textContainer">{text}</div>
);
}
}
ReactDOM.render(
<UnderlinedText text='Hello\n this is a test' />,
document.getElementById("root")
);
.textContainer {
white-space: pre-line;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
does not create the new lines and the string in debug has all the new line symbols ("\n") in it.
Where is the difference between those two solutions? And how to solve it?
this.props.textcontain?