Skip to main content

Conditional Rendering Techniques (Part 1): `if/else` and Ternaries #38

πŸ“– Introduction​

We've learned how to display data with props and render lists with .map(). Now, let's explore another fundamental aspect of creating dynamic UIs: conditional rendering. Your components will often need to display different things depending on the situationβ€”a user's login status, whether a list has items, or if a certain prop is true.

In React, there's no special syntax for this. You just use standard JavaScript. This article will cover the two most foundational techniques: using if/else statements and the conditional (ternary) operator.


πŸ“š Prerequisites​

Before we begin, please ensure you have a solid grasp of the following concepts:

  • React Components and Props: You should be comfortable creating components and passing props.
  • JavaScript Conditionals: You must know how if/else statements and the ternary operator (? :) work in JavaScript.
  • Embedding JavaScript in JSX: You should be familiar with using {} to embed expressions in JSX.

🎯 Article Outline: What You'll Master​

In this article, you will learn:

  • βœ… The Core Principle: Understanding that conditional rendering in React is just JavaScript.
  • βœ… Using if/else Statements: How to use standard if/else blocks to return entirely different JSX from a component.
  • βœ… Using Variables for Conditional JSX: A flexible pattern where you use if/else to assign JSX to a variable, which you then render.
  • βœ… The Ternary Operator (? :): A concise, inline way to choose between two JSX expressions.

🧠 Section 1: The Core Concept: It's Just JavaScript​

React doesn't invent its own special syntax for handling conditions (unlike some other frameworks that might have an x-if attribute). Instead, you use the full power of JavaScript to control your UI logic.

This means you can use:

  • if/else statements
  • The conditional (ternary) operator (? :)
  • The logical AND operator (&&)
  • switch statements

This article will focus on the first two, which are the most common and fundamental.


πŸ’» Section 2: Using if/else Statements​

An if statement is a great way to handle conditional logic when the two outcomes are significantly different. You can use it to return a completely different JSX tree from your component.

Let's create a LoginStatus component that shows a "Log In" button for guests and a "Log Out" button for users who are logged in.

// code-block-1.jsx
import React from 'react';

function LoginButton({ onClick }) {
return <button onClick={onClick}>Log In</button>;
}

function LogoutButton({ onClick }) {
return <button onClick={onClick}>Log Out</button>;
}

// This component uses an if/else statement to return one of two different components.
function LoginStatus({ isLoggedIn }) {
if (isLoggedIn) {
return <LogoutButton />;
} else {
return <LoginButton />;
}
}

export default function App() {
// In a real app, this would come from state
const loggedIn = true;
return <LoginStatus isLoggedIn={loggedIn} />;
}

Code Breakdown:

  1. function LoginStatus({ isLoggedIn }): The component receives a boolean isLoggedIn prop.
  2. if (isLoggedIn): We use a standard if statement to check the value of the prop.
  3. return <LogoutButton />: If the condition is true, the component returns early with the LogoutButton JSX. The rest of the function is not executed.
  4. else { return <LoginButton />; }: If the condition is false, the else block is executed, returning the LoginButton JSX instead.

This pattern is very clear and easy to read, especially when the two possible outputs are completely different components.


πŸ› οΈ Section 3: Assigning JSX to a Variable​

Sometimes, only a small part of your component needs to change, while the rest of the structure remains the same. In this case, returning early might lead to duplicating the surrounding JSX.

A more flexible approach is to use an if statement to assign a piece of JSX to a variable, and then render that variable inside your main JSX tree.

Let's refactor our LoginStatus component to use this pattern.

// code-block-2.jsx
// ... (LoginButton and LogoutButton are the same)

function LoginStatus({ isLoggedIn }) {
let button; // Declare a variable with let

if (isLoggedIn) {
button = <LogoutButton />;
} else {
button = <LoginButton />;
}

// The surrounding JSX is now only written once.
return (
<div>
<h2>Welcome to the App!</h2>
{button} {/* Render the conditionally assigned component */}
</div>
);
}

This approach is more verbose for this simple example, but it becomes incredibly useful when the conditional part is just one piece of a much larger component, helping you avoid code duplication.


πŸš€ Section 4: The Ternary Operator (? :)​

When you need to decide between two expressions inside your JSX, you can't use an if statement because it's a statement, not an expression. This is the perfect use case for the conditional (ternary) operator.

The syntax is condition ? expressionIfTrue : expressionIfFalse.

Let's create a simple component that displays a different message depending on a prop.

// code-block-3.jsx
import React from 'react';

function PackingListItem({ name, isPacked }) {
return (
<li>
{isPacked ? name + ' βœ…' : name + ' ❌'}
</li>
);
}

export default function PackingList() {
return (
<section>
<h1>Packing List</h1>
<ul>
<PackingListItem isPacked={true} name="Space suit" />
<PackingListItem isPacked={false} name="Photo of Tam" />
</ul>
</section>
);
}

Code Breakdown:

  • {isPacked ? ... : ...}: We open a "JavaScript window" with curly braces.
  • isPacked ? name + ' βœ…': If isPacked is true, the expression evaluates to the item name with a checkmark.
  • : name + ' ❌': Otherwise, it evaluates to the item name with a cross mark.

You can even use it to render different JSX elements:

// You can also render different components
function PackingListItem({ name, isPacked }) {
return (
<li>
{isPacked ? <del>{name}</del> : name}
</li>
);
}

The ternary operator is extremely common in React for its conciseness. However, for complex, nested conditions, it can become hard to read. In those cases, falling back to assigning JSX to a variable is often a better choice.


πŸ’‘ Conclusion & Key Takeaways​

You've now learned the two most fundamental ways to render content conditionally in React. By leveraging standard JavaScript if/else statements and the ternary operator, you can create dynamic UIs that respond to any condition.

Let's summarize the key takeaways:

  • Use if/else for Major Differences: When you need to return a completely different component or a large, distinct block of JSX, a standard if/else statement is very clear and readable.
  • Use Variables for Flexibility: Assigning JSX to a variable with let allows you to conditionally prepare a piece of your UI before placing it inside a larger, static structure.
  • Use Ternaries for Inline Conditions: The ternary operator (? :) is the perfect tool for choosing between two expressions directly inside your JSX.
  • Readability is Key: Choose the technique that makes your component's intent the clearest. For complex, nested conditions, a ternary can become hard to read, and extracting the logic into a variable is often better.

Challenge Yourself: Create a Gate component that takes an isOpen prop. If isOpen is true, it should render the text "The gate is open." in green. If it's false, it should render "The gate is closed." in red. Try implementing this with both an if/else statement and a ternary operator.


➑️ Next Steps​

You've mastered if/else and ternaries. In the next article, "Conditional Rendering Techniques (Part 2)", we will explore some powerful shortcuts, including the logical && operator for rendering something or nothing, and how to handle rendering null.

Thank you for your dedication. Stay curious, and happy coding!


glossary​

  • Conditional Rendering: The process of displaying different UI elements or components based on certain conditions or state.
  • Ternary Operator: A JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy.

Further Reading​