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.
Your approaches didn't work for two reasons:
\n does not exist in HTML (JSX).+ 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>
You could use a fragment to wrap the string and a <br /> tag:
<div>
{this.props.string ? (
<>
{this.props.string}
<br />
</>
) : null}
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With