Using && is a standard way to conditionally render parts of a component depending on props and state. For example,
function MyComponent({ condition }) {
return (
<div>
<h1>Title</h1>
{condition && <ConditionalComponent />}
</div>
)
}
Here's another example that shows the h2 if the component is not part of the HomePage,
<div className="flex flex-1">
{!isHomePage && (
<h2 className="self-center ml-4 font-logo text-2xl font-bold text-sky-600">
Gravital<span className="text-amber-600">Visuals</span>
</h2>
)}
</div>
if condition is a truthy value, is rendered if condition is a falsy value, is not rendered
Why is that? It’s nothing React specific but rather a behavior of JavaScript and other programming languages called short-circuit evaluation. I.e., if the first operand (condition) is falsy, the AND operator (&&) stops and it does not evaluate the second operand (). This is a useful behavior in JavaScript and other languages, but it can be confusing when you’re new to React.
The short syntax of && is often preferred and it works. But! Just because you can doesn’t mean you should.
In our case from above, if condition evaluates to true or false, you get what you’d expect — is or is not rendered respectively. All good so far. However, if condition doesn’t evaluate to a boolean, it may cause trouble.
For example:
if condition is 0, 0 is displayed in the UI if condition is undefined, you’ll get an error: "Uncaught Error: Error(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null."
if condition is 0, 0 is displayed in the UI if condition is undefined, you’ll get an error: "Uncaught Error: Error(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null."
To avoid showing something you don’t want in the UI, such as 0, that could mess up the layout, use the JavaScript ternary operator instead. I.e.,
condition ? <ConditionalComponent /> : null;