j.doe j.doe - 10 months ago 118
React JSX Question

Conditional rendering with reactjs

I want to add a div to my render objects depending on a condition. Right now I am using this code

render() {
return (
<div>
{this.test === this.someValue ? <div> some view </div> : <div> /div>}
...... // other components
</div>
)
}


this is working but I don't like the
: <div> /div>
because I don't need it. Is there any way to just use an
if
instead of
if else
?

Answer Source

You can also use only the first condition and return your desired component right away since JavaScript has short-circuit evaluation.

render() {
  return (
    <div>
     {this.test === this.someValue && <div> some view </div>}
     ......
    </div> 
  )
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download