← Back

React.js + Next.js · Module 2. React Basics · Lesson 7

Conditional Rendering

Conditional rendering allows a React component to display different content depending on a condition.

In Pizza Palace, we may need to show:

  • an availability message based on pizza stock;
  • a discount badge only during a promotion;
  • different text for delivery and pickup;
  • a loading message while the menu is being fetched;
  • an error message when an order cannot be submitted.

React uses normal JavaScript conditions to decide what appears in the interface.

You will learn

  1. What conditional rendering is.
  2. How to use the logical AND operator &&.
  3. How to use the ternary operator ? :.
  4. How to render text and larger JSX structures conditionally.
  5. How React handles false, null, and undefined.
  6. How to use conditions with props and state.
  7. Which conditional rendering mistakes beginners should avoid.

REACT · 01

1. What Is Conditional Rendering?

Conditional rendering means choosing what to display by checking application data.

Example — Pizza Availability

const availableCount = 10;

function App() {
  return (
    <div>
      <h2>Margherita</h2>
      <p>
        {availableCount > 0 ? "Available to order" : "Sold out"}
      </p>
    </div>
  );
}

export default App;

Browser Result

Margherita

Available to order

The true branch displays the availability message.

availableCount > 0 checks whether at least one pizza can be ordered.

If the condition is true, React displays:

Available to order

Otherwise, it displays:

Sold out

The interface now responds to menu data.


REACT · 02

2. Logical AND Operator — &&

Use the logical AND operator && when content should appear only if a condition is true.

Syntax

{condition && <Element />}

Remember: true → render the element; false → render nothing.

Example — Discount Badge

const discount = 20;

function App() {
  return (
    <div>
      <h2>Family Pizza</h2>

      {discount > 0 && (
        <p>Discount: {discount}%</p>
      )}
    </div>
  );
}

export default App;

Browser Result

Family Pizza

Discount: 20%

The discount paragraph appears because the condition is true.

Because 20 > 0 is true, the discount appears. If discount becomes 0, the paragraph disappears.

The expression must be inside JSX curly braces:

{discount > 0 && <p>Special offer!</p>}

REACT · 03

3. Conditional Rendering with Boolean Variables

Sometimes a condition is already stored as a boolean.

const isChefSpecial = true;

function App() {
  return (
    <div>
      <h2>Truffle Pizza</h2>

      {isChefSpecial && <p>Chef's special</p>}
    </div>
  );
}

export default App;

Browser Result

Truffle Pizza

Chef's special

The special label is visible while isChefSpecial is true.

isChefSpecial already contains true, so this is enough:

isChefSpecial && <p>Chef's special</p>

Writing isChefSpecial === true is valid but unnecessary.


REACT · 04

4. Conditional Content for Logged-In Customers

A pizza-ordering website may greet a returning customer.

const isLoggedIn = true;

function App() {
  return (
    <div>
      <h1>Pizza Palace</h1>

      {isLoggedIn && <p>Welcome back! Your saved addresses are ready.</p>}
    </div>
  );
}

export default App;

Browser Result

Pizza Palace

Welcome back! Your saved addresses are ready.

The welcome message appears only for a logged-in customer.

If isLoggedIn becomes false, the welcome message disappears.

Important Security Note

Conditional rendering controls the visible interface. It does not protect private data by itself.

Authentication, account data, order history, admin actions, and protected prices must also be secured by the backend. Hiding a button in React is not authorization.


REACT · 05

5. Ternary Operator — ? :

Use the ternary operator when there are two possible results.

Syntax

{condition ? resultIfTrue : resultIfFalse}

Example — Customer Message

const isLoggedIn = false;

function App() {
  return (
    <div>
      <h1>Pizza Palace</h1>

      <p>
        {isLoggedIn ? "Welcome back!" : "Log in to view previous orders"}
      </p>
    </div>
  );
}

export default App;

Browser Result

Pizza Palace

Log in to view previous orders

The false branch after the colon is displayed.

Because isLoggedIn is false, React displays the expression after :.


REACT · 06

6. Difference Between && and the Ternary Operator

Both operators can control rendered content, but they solve different problems.

Use && for One Optional Result

{hasFreeDelivery && <p>Free delivery!</p>}

If the condition is false, nothing is displayed.

Use a Ternary for Two Results

{isAvailable ? (
  <button>Add to cart</button>
) : (
  <p>Sold out</p>
)}

One of the two branches is rendered.

Operator Use it when
&& Something appears only when a condition is true
? : You must choose between two results

Browser Result

Free delivery!

The optional message comes from &&; the button is the true ternary branch.

REACT · 07

7. Rendering Different JSX Structures

A condition can choose between entire groups of JSX elements.

Example — Cart Summary

interface CartSummaryProps {
  customerName: string;
  items: string[];
}

function CartSummary(props: CartSummaryProps) {
  return (
    <section>
      <h2>Hello {props.customerName}</h2>

      {props.items.length > 0 ? (
        <>
          <p>You have {props.items.length} pizzas in your cart.</p>
          <p>Review the order before checkout.</p>
          <button>Open cart</button>
        </>
      ) : (
        <p>Your cart is empty.</p>
      )}
    </section>
  );
}

export default CartSummary;

Usage:

<CartSummary
  customerName="Nikita"
  items={["Margherita", "Pepperoni"]}
/>

Browser Result

Hello Nikita

You have 2 pizzas in your cart.

Review the order before checkout.

The non-empty cart branch renders a group of JSX elements.

When the array contains items, React displays two paragraphs and a button. When it is empty, React displays only Your cart is empty.

The Fragment <></> groups several elements without adding another HTML wrapper.


REACT · 08

8. React and false, null, undefined

React does not display false, null, or undefined as visible text when they are JSX children.

function App() {
  return (
    <div>
      {false}
      {null}
      {undefined}

      <p>Choose your pizza!</p>
    </div>
  );
}

Browser Result

Choose your pizza!

false, null, and undefined add no visible text.

Only Choose your pizza! is visible.

Returning null from a Component

A component can return null when it should display nothing.

interface OrderNoticeProps {
  visible: boolean;
}

function OrderNotice(props: OrderNoticeProps) {
  if (!props.visible) {
    return null;
  }

  return <p>Your order was added to the kitchen queue.</p>;
}

export default OrderNotice;

Browser Result when visible is true

Your order was added to the kitchen queue.

With visible=false, this entire message area is absent.

<OrderNotice visible={false} /> displays nothing. With visible={true}, React displays the message.


REACT · 09

9. Be Careful with Numbers and &&

Using a number directly on the left side of && can display an unwanted zero.

Potential Problem

const cartItems: string[] = [];

function App() {
  return (
    <div>
      {cartItems.length && <p>Your cart contains pizzas.</p>}
    </div>
  );
}

For an empty array, cartItems.length is 0. The expression returns 0, and React can display it.

Correct Solution

{cartItems.length > 0 && <p>Your cart contains pizzas.</p>}

Browser Result with an empty cart

The corrected boolean condition renders nothing and does not display an unwanted 0.

The explicit comparison produces true or false.

Rule: when using && with a number, write a boolean comparison such as count > 0.


REACT · 10

10. Conditional Rendering with Props

Reusable components can receive conditions through props.

interface PizzaCardProps {
  name: string;
  availableCount: number;
}

function PizzaCard(props: PizzaCardProps) {
  return (
    <article>
      <h2>{props.name}</h2>

      <p>
        {props.availableCount > 0 ? "Available" : "Sold out"}
      </p>
    </article>
  );
}

export default PizzaCard;

Usage:

<PizzaCard name="Margherita" availableCount={10} />
<PizzaCard name="Truffle Pizza" availableCount={0} />

Browser Result

Margherita

Available

Truffle Pizza

Sold out

Different prop values produce different availability messages.

The same component displays different messages because each instance receives different props.


REACT · 11

11. Conditional Rendering with State

Conditions can depend on React state.

Example — Show or Hide Ingredients

import { useState } from "react";

export default function PizzaDetails() {
  const state = useState(false);
  const showIngredients = state[0];
  const setShowIngredients = state[1];

  function toggleIngredients() {
    setShowIngredients(!showIngredients);
  }

  return (
    <section>
      <h2>Margherita</h2>

      <button onClick={toggleIngredients}>
        {showIngredients ? "Hide ingredients" : "Show ingredients"}
      </button>

      {showIngredients && (
        <p>Tomato, mozzarella, and basil</p>
      )}
    </section>
  );
}

Browser Result after selecting Show ingredients

Margherita

Tomato, mozzarella, and basil

After the state becomes true, the ingredients appear and the button label changes.

Initially, showIngredients is false. Clicking the button reverses the boolean value, React renders again, and the ingredients appear. Clicking again hides them.


REACT · 12

12. Using if Statements Outside JSX

Conditional rendering does not always require && or a ternary. Ordinary JavaScript if statements are often clearer for early returns.

interface AddToCartButtonProps {
  availableCount: number;
}

function AddToCartButton(props: AddToCartButtonProps) {
  if (props.availableCount === 0) {
    return <p>Sold out</p>;
  }

  return <button>Add to cart</button>;
}

export default AddToCartButton;

Browser Result when availableCount is 0

Sold out

The early return replaces the button with the sold-out message.

If the count is zero, the function returns the sold-out message immediately. Otherwise, it returns the button.

Use an if statement when it makes the component easier to read.


REACT · 13

13. Practical Application — Delivery or Pickup

At checkout, Pizza Palace can display different instructions for delivery and pickup.

interface FulfilmentMessageProps {
  method: "delivery" | "pickup";
  address?: string;
}

function FulfilmentMessage(props: FulfilmentMessageProps) {
  return (
    <section>
      <h2>Order method</h2>

      {props.method === "delivery" ? (
        <p>We will deliver to: {props.address ?? "Address required"}</p>
      ) : (
        <p>Your order will be ready for pickup at Pizza Palace.</p>
      )}
    </section>
  );
}

export default FulfilmentMessage;

Usage:

<FulfilmentMessage
  method="delivery"
  address="12 Market Street"
/>

Browser Result

Order method

We will deliver to: 12 Market Street

The delivery branch uses the address supplied through props.

This demonstrates UI behavior. A real ordering system must also validate the address and allowed delivery area on the backend.


REACT · 14

14. Common Beginner Mistakes

Mistake 1 — Double Curly Braces

Incorrect:

{{availableCount > 0 ? "Available" : "Sold out"}}

Correct:

{availableCount > 0 ? "Available" : "Sold out"}

Mistake 2 — Assignment Instead of a Condition

Incorrect:

{isChefSpecial = true && <p>Chef's special</p>}

Correct:

{isChefSpecial && <p>Chef's special</p>}

The assignment operator = changes a value. It is not a comparison.

Mistake 3 — Missing Colon in a Ternary

Incorrect:

{isAvailable ? "Add to cart"}

Correct:

{isAvailable ? "Add to cart" : "Sold out"}

Mistake 4 — Several Elements Without a Wrapper

Incorrect:

{isLoggedIn ? (
  <p>Welcome back</p>
  <button>View previous orders</button>
) : (
  <p>Please log in</p>
)}

Correct:

{isLoggedIn ? (
  <>
    <p>Welcome back</p>
    <button>View previous orders</button>
  </>
) : (
  <p>Please log in</p>
)}

Mistake 5 — A Number Directly with &&

Potentially problematic:

{cartCount && <p>Items in cart</p>}

Better:

{cartCount > 0 && <p>Items in cart</p>}

REACT · 15

15. Practice Exercises

Exercise 1 — Discount Badge

Create const discount = 20 and display Special discount: 20% only when the discount is greater than zero. Use &&.

Exercise 2 — Customer Message

Create const isLoggedIn = false. Display Welcome back! when true and Please log in when false. Use a ternary.

Exercise 3 — Pizza Availability

Create const availableCount = 0. Display Available to order when the count is greater than zero and Sold out otherwise.

Exercise 4 — Optional Order Notice

Create an OrderNotice component with a visible: boolean prop. Return null when visible is false.

Exercise 5 — PizzaCard Component

Create a reusable component receiving:

interface PizzaCardProps {
  name: string;
  price: number;
  isAvailable: boolean;
}

Display the pizza name and price. Use isAvailable to show either an Add to cart button or a Sold out message.

Exercise 6 — Delivery Choice

Create a state value that switches between delivery and pickup. Render the correct checkout instructions for the selected method.


REACT · 16

16. Key Takeaways

  • Conditional rendering lets React choose content based on application data.
  • Use && when content appears only for a true condition.
  • Use ? : to choose between two results.
  • Use an if statement when an early return is easier to read.
  • JSX conditional expressions use one pair of curly braces.
  • React does not display false, null, or undefined as visible children.
  • A component can return null to display nothing.
  • Compare numbers explicitly before using them with &&.
  • Conditions can use props or state.
  • Conditional rendering does not replace backend authorization or validation.

REACT · 17

17. Further Reading

Next lesson: Rendering Collections in React with .map() and key, using the Pizza Palace menu and cart.

← Back↑ Back to the top