Skip to content

Instantly share code, notes, and snippets.

@sparker888
Last active October 30, 2022 12:18
Show Gist options
  • Save sparker888/c03eb27405a199ec263e4662ee72bb71 to your computer and use it in GitHub Desktop.
Save sparker888/c03eb27405a199ec263e4662ee72bb71 to your computer and use it in GitHub Desktop.
React Layout Snippets

Stop Using “&&” for Conditional Rendering in React

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>

Briefly summarized:

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.

Why Not To Use “&&”

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."

Using && can be a problem. 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."

What To Use Instead Of “&&”

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;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment