user2190690 user2190690 - 5 months ago 26
Javascript Question

Reactjs render JSX with dynamic text value

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.

Answer

There couple ways how you can solve this issue

  1. use dangerouslySetInnerHTML

     let str = this.props.label.replace(/ /, '<br>');
     return <div dangerouslySetInnerHTML={ { __html: str} } />;
    

    Example

  2. 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>;
    

    Example