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?
Mikhail Katrin
2,4041 gold badge12 silver badges17 bronze badges
asked Nov 24, 2017 at 13:12
j.doe
4,9296 gold badges25 silver badges31 bronze badges
2 Answers 2
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>
)
}
answered Nov 24, 2017 at 13:14
Hemerson Carlin
7,4241 gold badge29 silver badges38 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
bluesixty
Here is a link to the react docs that outline all the conditional rendering schemes. reactjs.org/docs/conditional-rendering.html
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>
)
}
answered Nov 24, 2017 at 13:53
Shubham Khatri
284k58 gold badges431 silver badges411 bronze badges
Comments
lang-js
nullinstead of an emptydivas wellrecompose's branch. Have a look at it here : github.com/acdlite/recompose/blob/master/docs/API.md#branch