Conditional Rendering in React: Ternary & Short-Circuit

Master the art of creating dynamic and responsive UIs by telling your components what to render, and when.

Welcome! Let's make our React components smart enough to change what they display.

/* Starting the journey into dynamic UIs... */

The Ternary Operator: An If/Else in JSX

The ternary operator is a compact `if-else` statement directly inside your JSX. It takes a condition, a value for `true`, and a value for `false`. Its structure is condition ? expressIfTrue : expressIfFalse. It's perfect for switching between two components or values.

Logical AND (&&): Render or Nothing

The logical AND (`&&`) operator is ideal for rendering an element *only if* a condition is true. If the condition is false, it "short-circuits" and returns nothing. The syntax isLoggedIn && <Dashboard /> will only show the `Dashboard` when `isLoggedIn` is true.

Logical OR (||): Providing a Fallback

The logical OR (`||`) operator is often used to provide a fallback value. For example, userName || 'Guest' will display the `userName` if it exists (is "truthy"), otherwise, it will display 'Guest'. It's useful for preventing errors from null or undefined data.

The Result: A Dynamic UI

By combining these techniques with React's state, you can create highly dynamic and responsive user interfaces. When state changes (e.g., a user logs in), React re-renders the component, and your conditional logic will display the updated UI automatically.

Practice Zone


Interactive Test 1: Match the Concept

Match the React code snippet to its correct description.

Arrastra en el orden correspondiente.


Arrastra las opciones:

unreadMessages > 0 && <Badge />
displayName || 'Anonymous'
isOnline ? <p>Online</p> : <p>Offline</p>

Completa el código:

If/Else choice______
Render if true______
Fallback value______
Unlock with Premium

Interactive Test 2: Complete the Code

Rellena los huecos en cada casilla.

function UserStatus({ user }) {
  return (
    <div>
      {user.isLoggedIn  <p>Welcome!</p> : <p>Please log in.</p>}
      {user.hasNotifications  <span>You have new messages.</span>}
    </div>
  )
}
Unlock with Premium

Practice Example: Code Editor

Create a component that shows a "Loading..." message if the `isLoading` prop is true, otherwise it should show "Content Loaded".

Enunciado:

* Escribe el código a continuación. Los caracteres correctos se mostrarán en verde y los incorrectos en rojo.

function MyComponent({ isLoading }) { return ( <div> {isLoading ? <p>Loading...</p> : <p>Content Loaded</p>} </div> ); }

Unlock with Premium

Knowledge Check

Which operator is best for rendering a component only when a condition is true, and rendering nothing otherwise?


Unlock with Premium

Conditional Logic in Action

Conditional rendering is a core concept in React that allows you to build components that adapt to changing data. Here's how it connects with other fundamental React features.


1. Responding to State Changes

The most common use case is rendering UI based on component state. When you call a state setter function (like `setIsLoggedIn(true)`), React triggers a re-render, and your conditional logic is re-evaluated to show the new UI.

const [isOpen, setIsOpen] = useState(false);

// ...

{isOpen && <Modal />}
Modal Content

2. Conditional List Rendering

When mapping over an array to display a list, you can show a fallback message if the array is empty. This prevents a blank screen and improves user experience.

{items.length > 0 
  ? items.map(item => <li key={item.id}>{item.name}</li>)
  : <p>No items found.</p>
}
No items found.

3. Applying Conditional Styles

You can use ternary operators to dynamically apply CSS classes. This is perfect for styling active states, validation errors, or theme changes without complex logic.

<div className={`alert ${type === 'error' ? 'alert-error' : 'alert-success'}`}>
... 
</div>
Error Alert

Practical Takeaway: Mastering conditional rendering moves you from building static pages to creating truly interactive applications that respond intelligently to user actions and data changes.

Conditional Rendering Glossary

Conditional Rendering
The process in React of displaying different elements or components based on certain conditions, such as the component's state or props.
Ternary Operator (`? :`)
A JavaScript operator that provides a concise syntax for an `if-else` statement. Its format is `condition ? valueIfTrue : valueIfFalse`.
Short-Circuit Evaluation (`&&`, `||`)
A behavior of logical operators where the second operand is only evaluated if the first one is not enough to determine the result. In React, `condition && <Component />` uses this to render the component only if the condition is `true`.
JSX (JavaScript XML)
A syntax extension for JavaScript that allows you to write HTML-like code in your React components. It lets you embed JavaScript expressions (like ternaries) directly within curly braces ``.
Truthy / Falsy
In JavaScript, a value is "truthy" if it evaluates to `true` in a boolean context (e.g., numbers other than 0, non-empty strings, objects). A "falsy" value evaluates to `false` (e.g., `0`, `""`, `null`, `undefined`, `NaN`).