Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 5

Conditional Rendering in JSX

Recommended resources

Hello! Welcome to your fifth lesson in our "React Fundamentals and JSX" module.

In our last lesson, we established a crucial rule: you can only use JavaScript expressions inside JSX's curly braces {}. This allows us to inject dynamic values, but it also means we can't use multi-line if...else statements directly within our markup.

So, how do we show or hide components, or render different UI based on certain conditions? That's precisely what we'll cover today. This lesson fulfills the learning outcome: Apply conditional rendering using JavaScript operators and ternary expressions in JSX. We'll explore the common, idiomatic React patterns for bringing conditional logic into your components, building directly on your knowledge of JavaScript expressions.

The Two Main Scenarios for Conditional Rendering

In UI development, most conditional logic boils down to two scenarios:

  1. If-Else: You want to render Thing A if a condition is true, otherwise you render Thing B.
  2. If: You want to render Thing A if a condition is true, otherwise you render nothing.

Because React embraces using standard JavaScript, we can solve these with familiar JS operators.


1. The "If-Else" Case: Ternary Operator (? :)

The JavaScript ternary operator is a perfect fit for the if-else scenario. It's an expression, meaning it evaluates to a value, which makes it valid to use inside JSX's curly braces.

The syntax is condition ? expressionIfTrue : expressionIfFalse.

The official React documentation has a clear section on this.

Conditional Rendering

Let's start with the official React docs, 'Conditional Rendering', to see how the ternary operator provides a compact way to handle if-else logic directly within your JSX.

Read the section titled 'Conditional (ternary) operator (? :)'. It demonstrates how to replace a more verbose if/else return with a clean, inline ternary expression.

Let's apply this. Imagine a LoginButton component that shows "Logout" if the user is logged in, and "Login" otherwise.

// In a component file, e.g., LoginStatus.tsx

type LoginStatusProps = {
  isLoggedIn: boolean;
};

function LoginStatus({ isLoggedIn }: LoginStatusProps) {
  return (
    <div>
      <p>
        The user is currently {isLoggedIn ? 'logged in' : 'logged out'}.
      </p>
      <button>
        {isLoggedIn ? 'Log Out' : 'Log In'}
      </button>
    </div>
  );
}

export default LoginStatus;

Here, we use the ternary operator twice: once to render text and once to set the button's label. This is a very common and powerful pattern in React.


2. The "If" Case: Logical AND Operator (&&)

What if you want to show something or nothing? For example, displaying an error message only when an error exists. You could use a ternary condition ? <Component /> : null, but there's an even more common shortcut: the logical AND (&&) operator.

This pattern leverages JavaScript's "short-circuiting" behavior. In an expression A && B, if A is falsy, the expression immediately evaluates to A and B is never checked. If A is truthy, the expression evaluates to B.

React renders nothing for false, null, undefined, and empty strings. So, if your condition is false, the whole expression becomes false, and React renders nothing. If it's true, the expression becomes the JSX on the right, which React then renders.

Conditional Rendering

Let's return to the 'Conditional Rendering' documentation to see this && pattern in action.

Read the section 'Logical AND operator (&&)'. It explains how this operator is used to conditionally include a piece of JSX or render nothing.

Here's an example showing a "New" badge next to a product if it's a recent addition.

type ProductDisplayProps = {
  name: string;
  isNew: boolean;
};

function ProductDisplay({ name, isNew }: ProductDisplayProps) {
  return (
    <h2>
      {name} {isNew && <span style={{ color: 'red' }}> (New!)</span>}
    </h2>
  );
}

// Renders: <h2>Awesome Gadget <span style="color:red"> (New!)</span></h2>
// <ProductDisplay name="Awesome Gadget" isNew={true} />

// Renders: <h2>Old Gadget </h2>
// <ProductDisplay name="Old Gadget" isNew={false} />

The && Pitfall: The Problem with Zero

There's a critical detail to be aware of when using &&. What happens if the left-hand side of the expression is the number 0?

Since 0 is a falsy value in JavaScript, you might expect 0 && <Component /> to render nothing. However, the expression short-circuits and evaluates to 0. Unlike false, null, or undefined, React renders the number 0 in the DOM!

This commonly happens when checking the length of an array: messages.length && <MessageList />. If the array is empty, messages.length is 0, and your UI will unexpectedly display a "0".

This is a perfect opportunity to dive deeper into the underlying JavaScript principles. The following video explains this issue and the best practices to avoid it. Your background in JS will make this deep dive particularly insightful.

ReactJS Conditional Rendering // Principle && Best practices

The video 'ReactJS Conditional Rendering // Principle && Best practices' provides an excellent explanation of JavaScript's falsy values, how React treats them, and why using numbers with the && operator can lead to bugs.

Watch from the beginning to 8:36. Pay close attention to: The list of falsy values and which ones React renders (0:00 - 2:11). The concept of && short-circuiting (2:11 - 5:30). The demonstration of the 'zero' bug and two elegant solutions: using a ternary operator or the !! (double-NOT) operator (5:30 - 8:36).

As the video explains, the two robust ways to fix this are:

  1. Be explicit with a boolean expression: messages.length > 0 && <MessageList />. This is the most readable and is generally recommended.
  2. Convert the number to a boolean: !!messages.length && <MessageList />. The double-NOT or "double-bang" operator explicitly coerces any value to true or false. !!0 becomes false, neatly solving the problem. This is a concise pattern you'll often see in codebases.
Test your understanding!

You have a cartItems array. You want to render a <div> showing the number of items, but only if the cart is not empty. Which of these implementations are safe (i.e., will not render "0" when the cart is empty)?

  1. {cartItems.length && <div>You have {cartItems.length} items</div>}
  2. {cartItems.length > 0 && <div>You have {cartItems.length} items</div>}
  3. {!!cartItems.length && <div>You have {cartItems.length} items</div>}
  4. {cartItems.length ? <div>You have {cartItems.length} items</div> : null}
Show answer

Options 2, 3, and 4 are safe.

  1. Unsafe: If cartItems.length is 0, this expression evaluates to 0, and React will render "0".
  2. Safe: cartItems.length > 0 evaluates to the boolean false when the length is 0. React renders nothing for false.
  3. Safe: !!cartItems.length evaluates to the boolean false when the length is 0.
  4. Safe: The ternary explicitly returns null when the condition is falsy, which React renders as nothing.

Beyond Operators: Using Variables for Readability

When your conditional logic becomes complex, nesting ternaries can make the code hard to read.

{isLoading ? <Spinner /> : (error ? <Error /> : <Data />)}

This is functional, but not very clear. In these cases, remember that a React component is just a JavaScript function. You can use standard if statements or even switch cases before the return statement to prepare your content.

Conditional Rendering

For more complex scenarios, assigning JSX to a variable is a cleaner approach. The React documentation shows how this pattern improves readability.

Read the final section, 'Conditionally assigning JSX to a variable'. This shows how to use a let variable with if statements to prepare content before rendering.

Let's refactor the nested ternary from above using this more readable pattern:

function DataFetcher() {
  const { isLoading, error, data } = useSomeDataFetchingHook(); // Fictional hook

  let content: React.ReactNode;

  if (isLoading) {
    content = <p>Loading...</p>;
  } else if (error) {
    content = <p>Error: {error.message}</p>;
  } else {
    content = <ul>{/* Render data here */}</ul>;
  }

  return (
    <div>
      <h1>My Data</h1>
      {content}
    </div>
  );
}

This code is more verbose, but its logic is much easier to follow. For multiple, distinct cases, you could even use a switch statement or a map object to select the component to render, which are patterns you might appreciate from your general programming experience.


Conclusion

You now have a powerful toolkit for controlling what your React application renders and when. By combining your JavaScript knowledge with these idiomatic React patterns, you can create dynamic and responsive user interfaces.

Key Takeaways:

  • Use the ternary operator (? :) for simple if-else logic directly within JSX.
  • Use the logical AND operator (&&) to render an element or nothing.
  • Beware the '0' pitfall with &&. Always ensure the left-hand side evaluates to a boolean (e.g., count > 0) or use a ternary.
  • For complex logic, don't be afraid to use if/else statements and variables before the return statement to improve readability.

In our next lesson, we will explore another fundamental dynamic rendering technique: rendering lists of elements using the .map() function and key props. This will allow us to render UI based on collections of data, like a list of anime characters or search results.