Conditional Rendering

By Syncfusion®, Inc. · Last updated

Showing different things based on a condition: if statements, the ternary operator, the && operator, rendering based on state, and loading and error states.

Why Conditional Rendering?

Conditional rendering means showing different things on the screen depending on a condition. For example, show "Log out" when the user is logged in, and "Log in" when they are not.

In React, you write conditions with normal JavaScript: if, the ? : operator, and the && operator. This lesson shows when to use each one.

Real-World Example

A bookshop page checks the user and the data before it shows anything. While the books load, it shows "Loading…". If the list is empty, it shows "No books found".

A signed-in user sees My orders in the menu, and a guest sees Sign in. Each check is an if, && or ? : in the component, not a separate page.

One condition, two possible screens: if isOpen is true show Open, otherwise show Closed

isOpen ?

true false

Open

Closed

One condition decides which of the two screens is shown.

React has no special syntax for conditions. You use normal JavaScript inside your component.

if Statements

Use an if statement before the return, to choose which TSX to return. This is best when the two screens are very different.

You cannot put if inside the TSX braces { }. It must go before the return.

Look at ShopSign. If isOpen is true, the first return runs and the function stops there. If not, the second return runs.

Returning null

A component can show nothing by returning null. This is useful when a component should hide itself.

function SaleBanner({ onSale }: { onSale: boolean }) {
  if (!onSale) {
    return null; // show nothing
  }
  return <p>Big sale today!</p>;
}

Ternary Operators

The ternary operator ? : chooses between two values in one line. Because it gives back a value, you can use it inside the TSX braces { }.

condition ? valueIfTrue : valueIfFalse

Read it as: "Is the condition true? If yes, use the first value. If no, use the second value."

Click the button. Three things change, and all three use ? :: the heading text, the button text, and the paragraph.

When each part has more than one line of TSX, wrap it in round brackets ( ), as in the last example.

Logical AND Operator

Sometimes you want to show something or nothing. For this, use the && operator.

{condition && <p>Shown only when the condition is true</p>}

It means: if the condition is true, show the TSX after &&. If it is false, show nothing.

At the start, the cart count is 0, so the orange badge is hidden. Click Add a book. The badge appears. Click it three times, and the free delivery message appears too.

Be Careful with Numbers

Do not put a plain number on the left of &&. If the number is 0, React shows the 0 on the screen.

{cartCount && <span>{cartCount}</span>}     // Wrong: shows "0" when the cart is empty
{cartCount > 0 && <span>{cartCount}</span>} // Right: shows nothing when the cart is empty

Use ? : when you want to show one thing or another thing. Use && when you want to show one thing or nothing.

Rendering Based on State

Most conditions in React check state. When the state changes, React runs the component again and shows the matching screen.

A state can have more than two values. Here, step can be "cart", "address" or "done", so the component shows one of three screens.

type Step = "cart" | "address" | "done" means step can only be one of these three words. If you make a spelling mistake, TypeScript warns you.

Loading States

Getting data, for example from a server, takes time. While you wait, show a loading state: a message like "Loading..." so the user knows something is happening.

You keep a true/false state, such as isLoading:

  1. Set isLoading to true when you start getting the data.
  2. Show "Loading..." while it is true.
  3. Set it to false when the data arrives, and show the data.

Click Load books. "Loading..." shows for a moment, and then the list appears.

Look at disabled={isLoading} on the button. While loading, the button cannot be clicked again.

fetchBooks only pretends to talk to a server. It waits 1.5 seconds and then gives back the books. You will learn to get real data in a later lesson.

Error States

Getting data can fail. For example, the internet may be down. When that happens, show an error state: a clear message that tells the user what went wrong.

Keep the error message in state. Use null to mean "no error".

Try both buttons. Load (works) shows the books. Load (fails) shows a red error message.

This component uses all three ways together:

  • if (isLoading) returns a whole different screen while loading.
  • {error && ...} shows the error message only when there is an error.
  • The list shows the books, or nothing when the list is empty.

Most screens that get data need three states: loading, error, and data. Plan all three from the start.

Common mistakes

MistakeWhat you seeFix
Writing if inside { } in TSXExpression expected.Use ? : or &&, or move the if before return
{count && <p>...</p>} with a numberA 0 shows on the screenWrite {count > 0 && <p>...</p>}
Forgetting the : part of a ternaryCompile errorAlways write both parts: a ? b : c
Returning undefined by forgetting returnNothing showsReturn TSX or null from every path
Not turning isLoading back to false after an error"Loading..." stays foreverSet isLoading to false after both success and failure
Not clearing the old error before trying againThe old error stays on screenCall setError(null) when you start loading
Very long nested ternaries a ? b : c ? d : eCode is hard to readUse if before return, or split into small components

Check Yourself

Exercises

What to Remember

  • Use if before return to choose between very different screens.
  • Use ? : to show one thing or another, and && to show one thing or nothing.
  • Screens that load data need three states: loading, error and data.

Next: List Rendering