Conditional Rendering in React

Showing and hiding parts of your components with if, ternaries and &&.

When building React components you'll often need to show something only some of the time, like a loading spinner while data loads or a logout button when a user is signed in. Since JSX is just JavaScript, you can use the same conditionals you already know.

Using if with an Early Return

When a whole component should look different, an if statement before the return is the easiest to read:

const Profile = ({ user, loading }) => {
if (loading) {
return <p>Loading...</p>
}
return <h1>Hello, {user.name}</h1>
}

If loading is true, the component returns early and the rest never runs. This also keeps you from trying to read user.name before user exists.

Using a Ternary

if statements can't go inside JSX, but ternaries can. Use one when you need to pick between two things inline:

const Header = ({ user }) => (
<header>
<a href="/">Home</a>
{user ? <button>Log out</button> : <button>Log in</button>}
</header>
)

The part before the ? is the condition. If it's truthy, the first element is rendered, and if not, the second one is.

Using &&

When there's nothing to show in the other case, && is shorter than a ternary with null:

const Inbox = ({ messages }) => (
<div>
<h1>Inbox</h1>
{messages.length > 0 && <p>You have {messages.length} new messages.</p>}
</div>
)

If the left side is false, React renders nothing. If it's true, it renders whatever is on the right side.

Watch Out for 0

There's one gotcha with &&. React skips false, null and undefined, but it does render the number 0:

// If messages.length is 0, this renders a "0" on the page
<div>{messages.length && <p>You have new messages.</p>}</div>
// This renders nothing
<div>{messages.length > 0 && <p>You have new messages.</p>}</div>

0 && anything returns 0, and React happily prints it. Comparing with > 0 turns the condition into a real true or false.

Returning null

A component can return null to render nothing at all. This comes in handy for things like banners that can be dismissed:

import React, { useState } from "react"
const Banner = ({ message }) => {
const [visible, setVisible] = useState(true)
if (!visible) return null
return (
<div className="banner">
{message}
<button onClick={() => setVisible(false)}>Dismiss</button>
</div>
)
}

Once visible is false the banner disappears, and the parent component doesn't have to know anything about it.

Which One to Use

  • Use an early return when the whole component changes.
  • Use a ternary when you're choosing between two elements.
  • Use && when you're choosing between something and nothing.

If a ternary starts nesting inside another ternary, that's usually a sign to move the logic above the return or into its own component.

Have some feedback on this post? .