Four ways of conditional rendering
(In functional component's return statement or class component's render function's return statement)
Â
Ternary operator
Â
return (
<div>
{
'a'==='a' ? <p>Hi</p> : <p>Bye</p>
}
</div>
)
Note: Only if the condition 'a'==='a' is true, <p>Hi</p> will be rendered in the screen. Otherwise, <p>Bye</p> will be rendered on the screen.
Â
Logical operator
Â
AND &&
return (
<div>
{
'a'==='a' && <p>Hi</p>
}
</div>
)
Note: Only if the condition 'a'==='a' is true, <p>Hi</p> will be rendered in the screen.
Â
OR ||
export default function LogicalOperatorExample({name, labelText}) {
return (
<div>
{labelText || name}
</div>
)
}
Note: If labelText and name both props are passed into this component, then labelText will be rendered in the screen. But if only one of them (name or labelText ) is passed as prop, then that passed prop will be rendered in the screen.
Â
if, else, else if
Â
return (
<div>
{
(() => {
if('a'==='b') {
return (
<p>Hi</p>
)
} else if ('b'==='b') {
return (
<p>Hello</p>
)
} else {
return (
<p>Bye</p>
)
}
})()
}
</div>
)
Note: Have to use an anonymous functions (also need to immediately invoke the function )
Â
Switch statement
Â
return (
<div>
{
(() => {
switch(true) {
case('a'==='b'): {
return (
<p>Hello</p>
)
}
break;
case('a'==='a'): {
return (
<p>Hi</p>
)
}
break;
default: {
return (
<p>Bye</p>
)
}
break;
}
})()
}
</div>
)
Note: Have to use an anonymous functions (also need to immediately invoke the function)