Agentic hosting is here. Connect to our MCP now ->

Blog

Mastering React conditional rendering: a deep dive

In React, conditional rendering works the same way conditions work in JavaScript.

ยทby Joel Olawanle

Conditional rendering is a powerful feature in React that allows developers to render components based on certain conditions.

It is a fundamental concept that plays a crucial role in building dynamic and interactive web applications.

In this comprehensive guide, we will dive deep into conditional rendering in React, covering basic and advanced techniques with examples for proper understanding. The examples were tested with React 19 and React Router 8.

Understanding conditional rendering in React

Conditional rendering in React allows developers to dynamically control what content is displayed on the screen based on specific values which can be stored in a variable, state, or props.

This can be extremely useful in scenarios where you want to show or hide certain UI elements, change the layout of a page, or render different content based on user interactions.

Conditional rendering is important in React applications because it enables you to create dynamic and interactive user interfaces that can respond to changing data and user interactions in real time.

In React, conditional rendering works the same way conditions work in JavaScript. A component is a function that returns JSX, so you can use any JavaScript technique, such as if statements, the ternary operator, or logical operators, to decide what it returns.

Basic techniques for conditional rendering

There are several basic techniques that you can use for conditional rendering in React. Let's explore each of them in detail.

Using the if statement for conditional rendering

One of the most straightforward ways to implement conditional rendering in React is by using the traditional if statement.

if (condition) {
  return <p>Expression 1</p>;
} else {
  return <p>Expression 2</p>;
}

You can use JavaScript's if statement in the body of your component, before the return statement, to return different content depending on a condition. You can't use if inside JSX itself, because JSX only accepts expressions, but you can return early from the component.

For example, you can use the if statement to display a loading spinner while waiting for data to load:

import { useState, useEffect } from 'react';
import Spinner from './Spinner';
 
const MyComponent = () => {
  const [isLoading, setIsLoading] = useState(true);
  const [data, setData] = useState(null);
 
  useEffect(() => {
    // Fetch data from an API
    fetch('https://example.com/data')
      .then((response) => response.json())
      .then((data) => setData(data))
      .finally(() => setIsLoading(false));
  }, []);
 
  if (isLoading) {
    return <Spinner />;
  }
 
  return <div>{/* Render the data here */}</div>;
};
 
export default MyComponent;

In this example, MyComponent fetches data from an API using the useEffect hook. While waiting for the data to load, we display a Spinner component using the if statement. The finally() call turns off the loading state whether the request succeeds or fails, so the spinner never gets stuck.

Another example is rendering a fallback message when data is missing:

const MyComponent = ({ data }) => {
  if (!data) {
    return <p>Something went wrong. Please try again later.</p>;
  }
 
  return <div>{/* Render the data here */}</div>;
};
 
export default MyComponent;

In this code, we have a MyComponent that takes a data prop. If the data prop is falsy, we render an error message using the if statement.

You can also display different content for different user roles with the if statement:

const MyComponent = ({ user }) => {
  if (user.role === 'admin') {
    return <p>Welcome, admin!</p>;
  } else if (user.role === 'user') {
    return <p>Welcome, user!</p>;
  } else {
    return <p>You are not authorized to access this page.</p>;
  }
};
 
export default MyComponent;

In this code, we have a MyComponent that takes a user prop. Depending on the user.role property, we display different content using the if statement.

Rendering nothing with null

Sometimes, you don't want a component to render anything at all. In that case, return null:

const Banner = ({ show }) => {
  if (!show) {
    return null;
  }
 
  return <p>Free shipping on all orders this week!</p>;
};

When show is false, Banner renders nothing. Returning null doesn't stop the component's hooks from running, though, so the component still exists in the tree. To remove it entirely, use conditional rendering in its parent instead.

Using the ternary operator for conditional rendering

Another concise way to implement conditional rendering in React is by using the ternary operator (? :) inside JSX.

The ternary operator allows you to write a compact inline if-else statement by specifying 3 operands. The first operand is the condition, while the other two operands are the expressions. If the condition is true, the first expression is used; otherwise, the second expression.

For example, you can render different components based on a prop:

import ComponentA from './ComponentA';
import ComponentB from './ComponentB';
 
const ExampleComponent = ({ shouldRenderComponentA }) => {
  return (
    <div>
      {shouldRenderComponentA ? <ComponentA /> : <ComponentB />}
    </div>
  );
};
 
export default ExampleComponent;

In this code, we have an ExampleComponent that takes a prop called shouldRenderComponentA. We use the ternary operator to conditionally render either ComponentA or ComponentB based on the prop value.

You can also render different text based on a state:

import { useState } from 'react';
 
const ExampleComponent = () => {
  const [showMessage, setShowMessage] = useState(false);
 
  return (
    <div>
      <button onClick={() => setShowMessage(!showMessage)}>
        {showMessage ? 'Hide message' : 'Show message'}
      </button>
      {showMessage ? <p>Hello, world!</p> : null}
    </div>
  );
};
 
export default ExampleComponent;

In this example, we use the ternary operator to conditionally render different text depending on the value of the showMessage state. When the button is clicked, the value of showMessage is toggled, and the text is displayed or hidden accordingly.

Finally, you can render a loading spinner while data is being fetched:

import { useState, useEffect } from 'react';
import Spinner from './Spinner';
 
const ExampleComponent = () => {
  const [isLoading, setIsLoading] = useState(true);
  const [data, setData] = useState(null);
 
  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
      const jsonData = await response.json();
      setData(jsonData);
      setIsLoading(false);
    };
    fetchData();
  }, []);
 
  return (
    <div>
      {isLoading ? <Spinner /> : <p>{data.title}</p>}
    </div>
  );
};
 
export default ExampleComponent;

In this example, we use the ternary operator to conditionally render a loading spinner while data is being fetched from an API. Once the data is available, we render its title property instead.

Using logical AND and OR operators for conditional rendering

You can also use the logical AND (&&) and OR (||) operators to implement conditional rendering in React.

The logical AND operator allows you to render something only if a condition is true, while the logical OR operator lets you fall back to an alternative value when the first one is falsy.

These operators are useful when you have simple conditions that determine whether a component should be rendered or not. For example, if you want to render a button only if a form is valid, you can use the logical AND operator like this:

import { useState } from 'react';
 
const FormComponent = () => {
  const [formValues, setFormValues] = useState({ username: '', password: '' });
 
  const isFormValid = formValues.username !== '' && formValues.password !== '';
 
  const handleSubmit = (event) => {
    event.preventDefault();
    // Submit form data
  };
 
  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={formValues.username}
        placeholder="Type Username..."
        onChange={(e) =>
          setFormValues({ ...formValues, username: e.target.value })
        }
      />
      <br />
      <input
        type="password"
        value={formValues.password}
        placeholder="Type Password..."
        onChange={(e) =>
          setFormValues({ ...formValues, password: e.target.value })
        }
      />
      {isFormValid && <button type="submit">Submit</button>}
    </form>
  );
};
 
export default FormComponent;

In this example, we have a FormComponent that has a form with two input fields for username and password. We're using the useState hook to manage the form values and the isFormValid variable to check if both input fields have values. Using the logical AND operator (&&), we render the submit button only if isFormValid is true, so the button appears only when the form is filled in.

Watch out for 0 with the && operator

The && operator has a common pitfall. JavaScript's && returns the left-hand value when it's falsy, and React renders numbers, including 0. So if the left side can be 0, React displays it:

const Inbox = ({ messages }) => (
  <div>
    {messages.length && <p>You have {messages.length} new messages</p>}
  </div>
);

If messages is an empty array, messages.length is 0, and React renders the 0 on the page: the component outputs <div>0</div> instead of an empty div. To fix it, make sure the left side is a boolean:

{messages.length > 0 && <p>You have {messages.length} new messages</p>}

Other falsy values, such as false, null, undefined, and an empty string, don't render anything, so this problem only affects numbers.

Similarly, you can use the OR operator to render a loading message if data is still loading or an error message if an error occurs:

import { useEffect, useState } from 'react';
 
const DataComponent = () => {
  const [data, setData] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [errorMessage, setErrorMessage] = useState('');
 
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch('https://api.example.com/data');
        const data = await response.json();
        setData(data);
      } catch (error) {
        setErrorMessage('An error occurred while fetching data.');
      } finally {
        setIsLoading(false);
      }
    };
 
    fetchData();
  }, []);
 
  return (
    <>
      {errorMessage || isLoading ? (
        <p>{errorMessage || 'Loading...'}</p>
      ) : (
        <ul>
          {data.map((item) => (
            <li key={item.id}>{item.name}</li>
          ))}
        </ul>
      )}
    </>
  );
};
 
export default DataComponent;

In this example, a DataComponent fetches data from an API using fetch and displays it in a list. We're using the useState hook to manage the data, loading state, and error message. The condition errorMessage || isLoading is true while the data loads or if an error occurs, and inside the paragraph, errorMessage || 'Loading...' shows the error message if there is one, and the loading message otherwise. This ensures that the user sees a message indicating the current state of the data fetching process.

Using the logical AND and OR operators for conditional rendering in React is a concise and readable way to handle simple conditions. However, for more complex logic, an if or switch statement before the return is usually easier to read.

Advanced techniques for conditional rendering

Conditional rendering in React can be more complex depending on the requirements of your application. Here are some advanced techniques that you can use for conditional rendering in more complex scenarios.

Using switch statements for conditional rendering

While if statements and ternary operators are common approaches for conditional rendering, sometimes a switch statement can be more appropriate, especially when dealing with multiple conditions.

Here's an example:

const MyComponent = ({ userType }) => {
  switch (userType) {
    case 'admin':
      return <p>Welcome, admin user!</p>;
    case 'user':
      return <p>Welcome, regular user!</p>;
    default:
      return <p>Please log in to continue.</p>;
  }
};
 
export default MyComponent;

In this code, a switch statement is used to render content based on the userType prop conditionally. This approach can be helpful when dealing with multiple conditions and provides a more organized and readable way to handle complex logic.

Conditional rendering with React Router

React Router is a popular library for handling routing in React applications. It renders different components depending on the current URL, which is a form of conditional rendering, and you can combine it with your own conditions, for example, to protect pages that require users to log in.

Here's an example with the current version of React Router:

import { useState } from 'react';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router';
 
import Home from './components/Home';
import Login from './components/Login';
import Dashboard from './components/Dashboard';
import NotFound from './components/NotFound';
 
function ProtectedRoute({ isLoggedIn, children }) {
  if (!isLoggedIn) {
    return <Navigate to="/login" replace />;
  }
 
  return children;
}
 
const App = () => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
 
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/login" element={<Login setIsLoggedIn={setIsLoggedIn} />} />
        <Route
          path="/dashboard"
          element={
            <ProtectedRoute isLoggedIn={isLoggedIn}>
              <Dashboard />
            </ProtectedRoute>
          }
        />
        <Route path="*" element={<NotFound />} />
      </Routes>
    </BrowserRouter>
  );
};
 
export default App;

Here's how it works:

  • <Routes> renders the first <Route> whose path matches the current URL, and each route's element prop sets what to render. The route with path="*" matches any other URL, so it shows the NotFound page.
  • The ProtectedRoute component uses an if statement to check the isLoggedIn state. If the user isn't logged in, it renders the <Navigate> component, which redirects to /login. Otherwise, it renders its children, the Dashboard.
  • The Login component receives setIsLoggedIn as a prop, and sets the state to true once the user logs in.

In React Router 6 and later, the Switch component and the component prop of older versions are replaced by Routes and the element prop. Also, since React Router 7, you import everything from the react-router package.

In a real app, you'd keep the logged-in state in a context or an authentication library, so that it survives page reloads, but the conditional rendering logic stays the same.

Summary

Conditional rendering is a powerful technique in React that allows you to dynamically update the UI based on different conditions.

Depending on the complexity of your application's UI logic, you can choose the approach that best fits your needs: if statements and early returns for whole components, the ternary operator for either-or choices inside JSX, && for showing or hiding a single element, and switch statements for many cases.

Remember to keep your code clean, organized, and readable, and always thoroughly test your conditional rendering logic to ensure it works as expected in different scenarios.

When your React app is ready, you can deploy it for free with Sevalla's Static Site Hosting, or use Application Hosting if it needs a server.

Deep dive into the cloud!

Deploy your application, database, or static site in minutes.