Rendering elements or components conditionally is something that we have to do often in React components.
There are a few ways to do this.
If we are rendering something is a condition it true
, then we can use the &&
operator:
{condition && <Component />}
When condition
is true
then Component
will render because the first operand being true
will lead to the 2nd expression being evaluated.
If we want to render something when a condition is true
and render something else otherwise, then we can use the ternary operator:
{condition ? <Component /> : <OtherComponent />}
If condition
is true
, then Component
will be rendered. Otherwise, OtherComponent
will be rendered.
This is handy for conditionals with 2 cases.
If our condition has more than 2 cases, then we have to use if/else or switch statements.
We can use if/else statements as follows:
let comp;
if (foo){
comp = <Component />;
}
else if (bar){
comp = <OtherComponent />;
}
else if (baz){
comp = <AnotherComponent />;
}
We assign comp
with the component we want according to the condition that we’ve encountered.
This is the most versatile way to render components based on different cases,
Also, we can use the switch
statement by writing:
switch (value){
case 1: {
comp = <Component />;
break;
}
case 2: {
comp = <OtherComponent />;
break;
}
case 3: {
comp = <AnotherComponent />;
break;
}
default: {
comp = <DefaultComponent />;
break;
}
}
We check the value of value
against various values and assign a component to comp
based on the value.
Also, we have a default
case so that we can render something if the value of value
doesn’t match any of the values listed in the case
blocks.
We can do conditional rendering with plain JavaScript.
For simple cases, we can use the &&
or ternary operators.
For more complex cases, we can use if/else or switch statements.