Inline Conditional Rendering in React
You can embed expressions containing logical AND (&&
) operator inside of JSX to conditionally render a component.
In JavaScript, an expression of operand1 && operand2
returns the value of operand2
if both of the operands evaluate to true
. Otherwise the first operand that evaluates to false
is returned.
const App = () => {
const isVisible = true;
return <>{isVisible && <Component />}</>;
};
If isVisible
and <Component />
evaluate to true then the {isVisible && <Component />}
expression returns the value of <Component />
and React renders that component.
Setting isVisible
to any falsy value makes the expression return the current value of isVisible
.
React doesn’t render some falsy values - false
and null
- but it does render 0
and ""
(empty string).
Writing the following code renders 0
when the items
array is empty.
const App = () => {
const items = [];
return <>{items.length && <List />}</>;
}
To prevent that from happening you have to make the first operand evaluate to a value that React doesn’t render.
You can turn items.length
into its corresponding boolean value by using logical NOT (!
) operator twice.
const App = () => {
const items = [];
return <>{!!items.length && <List />}</>;
}
You can also use the comparison operator to make the first operand return a boolean value.
const App = () => {
const items = [];
return <>{items.length > 0 && <List />}</>;
}