Reputation:
I have a component <Ren1 text="Line1\nLine2\nLine3" />
...
function Ren1({text}){
return <p>{text}</p>;
}
export default Ren1
How do I add the line break from \n
from when it comes from the database?
Needed output:
Line1
Line2
Line3
Thank you in advance for your help
Upvotes: 3
Views: 4918
Reputation: 202608
Split the text prop on "\n" and map the result array into the p
tag within a Fragment
with br
element.
function Ren1({ text }) {
return (
<p>
{text.split("\\n").map((line, index) => (
<React.Fragment key={index}>
{line}
<br />
</React.Fragment>
))}
</p>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(
<Ren1 text="Line1\nLine2\nLine3" />,
rootElement
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Upvotes: 0
Reputation: 2968
You can do it without splitting the text value.
First, put curly braces around the text prop when you are passing it:
<Text text={"One \n Two \n Three"} />
Then use whiteSpace: "pre-line"
style
<div style={{ whiteSpace: "pre-line" }}>{props.text}</div>
Upvotes: 8
Reputation: 101
You could create an array containing the actual text lines
with split
(i.e. const lines = text.split('\n')
).
Then you could map over this array to render the lines individually.
lines.map(line => ...)
Upvotes: 0