You can use regular if/else conditions inside a component render. The conditional (ternary) operator is your friend. Although, as the markup gets larger or more varied - it is advisable to split it up into separate components and use them instead.
//if
function render() {
return condition && <span>Rendered when `truthy`</span>
}
// unless
function render() {
return condition || <span>Rendered when `falsey`</span>
}
// if- else (tidy one - liners)
function render() {
return condition
? <span>Rendered when `truthy`</span>
: <span>Rendered when `falsey`</span>
}
// if- else (big blocks)
function render() {
return condition ? (
<span>
Rendered when `truthy`
</span>
) : (
<span>
Rendered when `falsey`
</span>
)
}
Note that if you use falsy or truthy values (as opposed to booleans) combined with logical operators, they can show up in your page:
const Oops = ({showFirst, dontShowSecond}) => (
<div>
{showFirst && 'first'}
{dontShowSecond || 'second'}
</div>
)
if you use <Oops showFirst={0} dontShowSecond={1}/>
you will get 01
instead of the empty space you may be expecting.
This can be avoided using !! to convert values to boolean before use:
const Oops = ({showFirst, dontShowSecond}) => (
<div>
{!!showFirst && 'first'}
{!!dontShowSecond || 'second'}
</div>
)