We always use the follow two ways to conditional render in JSX:
- Ternary(Conditional) operator
render() {
return (
<div>
xxx
<div>{ shouldShow ? 'Hey' : null }</div>
xxx
</div>
);
}
- Logical conjunction
render() {
return (
<div>
xxx
<div>{ shouldShow && 'Hey'}</div>
xxx
</div>
);
}
false
, null
, undefined
, and true
are valid children. They will be ignored( and skips the second expression), and simply don't render. These JSX expressions will all render to the same thing:
<div />
<div></div>
<div>{false}</div>
<div>{null}</div>
<div>{undefined}</div>
<div>{true}</div>
This JSX only renders the string Hey
only when shouldShow
is true:
And one thing special is that, when shouldShow is an integer 0
:
For ternary operator, it will not render any thing.
For logical conjunction, it will rend an integer 0
there.
Actually, there are multiple ways to conditional show, if you are interesting with them, checkout them here.
if statement
ternary operation
logical && operator
switch case operator
enums
Multi-Level Conditional Rendering
With Higher Order Components
External Templating Components