Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 258
buratino Avatar asked Mar 07 '26 17:03

buratino


2 Answers

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>
like image 78
Tobias Tengler Avatar answered Mar 09 '26 05:03

Tobias Tengler


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

<div>
    {this.props.string ? (
      <>
        {this.props.string}
        <br />
      </> 
    ) : null}
</div>
like image 21
zackkrida Avatar answered Mar 09 '26 05:03

zackkrida



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!