Toni Leigh
Toni Leigh

Reputation: 4971

Outputting plain text with <br /> tags in JSX

I'm trying to output the following HTML structure using React JS and JSX. I don't want to use dangerouslySetInnerHTML as this data is settable by our users.

Any of the lines could be missing as no piece of data is required and there should be no blank lines left such as would be if the data

<p>
  one<br />
  two<br />
  three<br />
  four
</p>

I currently have this:

<p className='address__details'>
  { this.line_1.length > 0 ? `${this.line_1}<br />` : `` }
  { this.line_2.length > 0 ? `${this.line_2}<br />` : `` }
  { this.line_3.length > 0 ? `${this.line_3}<br />` : `` }
  { this.line_4.length > 0 ? `${this.line_4}<br />` : `` }
</p>

As I understand tertiary conditions are required no if work inside of a JSX return statement. This just outputs text on the page, the <br /> tags are not interpreted as HTML.

Is it possible to output this as in my example or am I going to have to do away with the <br /> tags and use <div>s for the newlines?

Upvotes: 1

Views: 9761

Answers (4)

dimsuz
dimsuz

Reputation: 9207

You can do this more or less elegantly by using for-loop and push-ing text line and <br/> separately:

const textLines = [ "one", "two", "three", "four" ]
const lines = []
for (var item of textLines) {
  lines.push(item)
  lines.push(<br/>)
}
return (<p>{lines}</p>)

Upvotes: 0

Darkhan ZD
Darkhan ZD

Reputation: 610

Here is my function, works only for BR tags

function textToHtml(html)
{
    let arr = html.split(/<br\s*\/?>/i);
    return arr.reduce((el, a) => el.concat(a, <br />), []);
}

How to use:

<p>{textToHtml(this.state.text)}</p>

Upvotes: 1

Radio-
Radio-

Reputation: 3171

While not particularly elegant, you could do this

{ this.line_1.length > 0 ? `${this.line_1}` : `` }{ this.line_1.length > 0 ? <br /> : null}

Upvotes: 0

robertklep
robertklep

Reputation: 203359

Any HTML markup inside strings will be escaped, so you're going to have to properly wrap the lines with a container element:

{ this.line_1.length > 0 ? <p>{ this.line_1 }</p> : null }

Upvotes: 0

Related Questions