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