0

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?

2

2 Answers 2

7

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> 
  )
}
Sign up to request clarification or add additional context in comments.

1 Comment

Here is a link to the react docs that outline all the conditional rendering schemes. reactjs.org/docs/conditional-rendering.html
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.