Suppose I have a text string that contains line-breaks, and I render it like this:
render() { var text = "One\nTwo\nThree"; return <div>{text}</div>; }
In HTML the line-breaks don't render as line-breaks. How should I do this in React? I don't want to convert to <br>
tags and use dangerouslySetInnerHTML
. Is there another way?
In the ReactDOM. render you still can't render multiple items because react needs a root. So you can render a single component inside the ReactDOM. render and render an array of items in the internal component.
To wrap React Native text on the screen, we can set flexWrap to 'wrap' .
Fragments in React Now you can render multiple DOM nodes. In order to do this, wrap it inside a parent div which essentially makes it a single DOM node with multiple elements inside it. Fragments in React do not deviate much from their literal meaning.
Make a new CSS-class
.display-linebreak { white-space: pre-line; }
Display your text with that CSS-class
render() { const text = 'One \n Two \n Three'; return ( <div className="display-linebreak"> {text} </div> ); }
Renders with line-breaks (Sequences of whitespace will collapse into a single whitespace. Text will wrap when necessary). Like this:
One Two Three
You may also consider pre-wrap. More info here (CSS white-space Property).
You could try putting divs for each line
render() { return (<div> <div>{"One"}</div> <div>{"Two"}</div> <div>{"Three"}</div> </div>); }
Or
render() { var text = "One\nTwo\nThree"; return ( <div> {text.split("\n").map((i,key) => { return <div key={key}>{i}</div>; })} </div>); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With