3

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.

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.