j.doe
j.doe

Reputation: 4859

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?

Upvotes: 0

Views: 142

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 281686

Instead of returning an empty div just because you have to have a second condition, you could return null instead like

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

Upvotes: 0

Hemerson Carlin
Hemerson Carlin

Reputation: 7424

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> 
  )
}

Upvotes: 7

Related Questions