Skip to content

Conditional Rendering

beginner2 min read
  • React

Showing different UI depending on the current data or state, using ordinary JavaScript conditions such as if, the ternary operator, and logical AND.

Prerequisites

  • JSX and expressions (see Related Topics)

What you'll understand

  • How to render different UI based on a condition
  • The common ways to write conditions in JSX
  • When to render nothing at all

Explanation

Conditional rendering is showing different markup depending on the situation: a spinner while data loads, an error message on failure, the content on success. React does not add special syntax for this; you use ordinary JavaScript, because a component is just a function that returns markup, and you can decide what to return.

There are three common patterns. Outside JSX you can use a plain if statement to return different markup, or assign to a variable. Inside JSX, where only expressions are allowed, you use the ternary operator (condition ? a : b) to choose between two options, or logical AND (condition && a) to render something only when a condition is true. Which you pick is mostly about readability.

Sometimes the right answer is to render nothing, and a component can return null to do exactly that. One caution with the && pattern: the left side must be a real boolean, because a value like 0 is falsy but still renders as the number 0. Converting to a boolean, or using a ternary, avoids that surprise.

Examples

A ternary chooses between two branches inside JSX:

function Status({ loading }: { loading: boolean }) {
  return <div>{loading ? <Spinner /> : <Content />}</div>;
}

Logical AND renders something only when the condition is true:

{errorMessage && <p className="error">{errorMessage}</p>}

Common mistakes

  • Using && with a number like count, which renders 0 when the count is zero.
  • Writing an if statement directly inside JSX, where only expressions are allowed.
  • Nesting ternaries so deeply the markup becomes unreadable.
  • Returning undefined to render nothing instead of null.

Best practices

  • Use a ternary for either/or UI and logical AND for show/hide.
  • Ensure the left side of && is a genuine boolean.
  • Move complex branching above the return statement for readability.
  • Return null when a component should render nothing.

Further reading

Related topics