buratino
buratino

Reputation: 1518

JSX within curly braces

I have a conditional statement to print a field if it is not null that I want followed by a line break. This statement exists within a <div></div>. It seems that <br /> (or any other jsx) cannot be used within {...} statements.

What I want to happen is to conditionally print my string and a newline if the condition is met. Below I will show what is actually happening.

<div>
    {this.props.string ? "$" + this.props.string + <br /> : null}
</div>

In this case, <br /> renders as [object Object].

I have also tried

<div>
    {this.props.string ? "$" + this.props.string + "\n" : null}
</div>

But "\n" is printed literally.

Why is <br /> being rendered as [object Object]? What do I need to do to achieve my desired result?

This question is different from the one found here in that I am looking for an inline solution rather than having to build an array with a single value.

Upvotes: 3

Views: 4614

Answers (3)

Tobias Tengler
Tobias Tengler

Reputation: 7454

Your approaches didn't work for two reasons:

  1. \n does not exist in HTML (JSX).
  2. When you use the + operator, e.g. "$" + this.props.string + <br />, the operands are evaluated from left to right. Because the operation starts with a string ("$") all other operands are treated as strings as well. In your example the <br/> (a React.Node / object) is converted to its string representation ([object Object]) and added to the string.

You could use a Fragment in combination with conditional inline rendering to make it work:

<div>
    {this.props.string && (
        <>
            {"$" + this.props.string}
            <br />
        </>
    )}
</div>

Upvotes: 8

AngelSalazar
AngelSalazar

Reputation: 3113

<div>
 {
   props.string
   ? <React.Fragment>test<br/></React.Fragment>
   : null
 }
</div>

Upvotes: 0

zackkrida
zackkrida

Reputation: 421

You could use a fragment to wrap the string and a <br /> tag:

<div>
    {this.props.string ? (
      <>
        {this.props.string}
        <br />
      </> 
    ) : null}
</div>

Upvotes: 2

Related Questions