Search code examples
javascriptreactjsstringstring-literalstemplate-literals

How to render a formatted template string in React instead of one paragraph?


I am setting my state as follows -

setMessage(color, text) {
        this.setState({ message: { color: color, text: text } });
    }

body = `These are your options to raise money:​
Increase your credit allowance (invite new people into the game, this increases your overdraft auto`

this.setMessage('red', `${body}` );

I am rendering it is {this.state.message.text}, however it doesn't render the multiple lines, instead it all gets squeezed into one paragraph.

How do I fix it and render it?


Solution

  • You can use Jsx to do that. I have also faced this issue, I solved it like this and it did work for me. You can use either React fragment tag or any valid jsx tag

    setMessage(color, text) {
            this.setState({ message: { color: color, text: text } });
        }
    
    body = <>These are your options to raise money:​<br />
    Increase your credit allowance (invite new people into the game, this increases your overdraft auto</>
    
    this.setMessage('red', body );