Reputation: 2044
I'm using ReactJS and I have the following problem that I can't find a solution to:
At the point just prior to render I would like to replace a space between two words with anything that will force a line break. So far everything I try doesn't work. I've read the React documentation which may be suggesting I'm dealing with a 'JSX Gotchas'
let strReturn = "\u000A";//<br/>//\u000D
// for example this.props.label could have a value of "Big Bid"
// now remove space between 'Big Bid' and replace with <br/>
let str = this.props.label.replace(/ /, strReturn );
return <div className={this.props.className}>{str}</div>
Presently what is rendered to screen includes text of say Big<br/>
Bid.
If there are any ReactJS pros that could show me the best way of dealing with this issue I'd be very grateful.
Many thanks in advance.
Upvotes: 3
Views: 3214
Reputation: 77512
There couple ways how you can solve this issue
let str = this.props.label.replace(/ /, '<br>');
return <div dangerouslySetInnerHTML={ { __html: str} } />;
split string and then wrap each line to tag, for instance <p>
let text = this.props.label.split(/ /).map((text, index) => {
return <p key={ index }>{ text }</p>
});
<div>
{ text }
</div>;
Upvotes: 4
Reputation: 8781
In this situation I'd actually go the route of being explicit with what you're trying to achieve, rather than relying on Unicode insertion tricks, or disabling escaping etc.
I would just split the string according to whitespace, and then, build a list of elements from it.
Upvotes: 1