Type to generate custom UI components with AI

Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

React Conditional Render: How to Use and Best Practices

Users interact with our applications in various ways, and to enhance the user experience, we must enable these processes to occur dynamically. React allows us to render user information dynamically and seamlessly with React conditional render.

In this article, we’ll explore the dynamic world of React. By the end of this article, you’ll learn how to display elements, components, and more based on specific conditions, creating an interactive and seamless user experience.

Prerequisites

This article assumes you have working experience with JavaScript and know how to render pages in a React application.

All source code is immediately usable in this article. Ensure you have a React app playground available to easily copy and paste the code for a hands-on experience.

You can set up a React app using Vite by following the instructions in the video below (skip to 2:51 for the installation guide).

What is Conditional Rendering in React?

Conditional rendering in React is the process of displaying elements, components, or any other contents on the interface of our applications based on conditions that are evaluated to be true or false.

Similar to Javascript, React’s conditional rendering uses switch statements, if-else, and ternary operators to render different items depending on the user’s actions or the current state of the application.

In the following sections, we’ll explore the various ways React helps developers render content conditionally and dynamically.

What are JavaScript Condition Operators?

Conditional operators, often referred to as Comparison Operators are used to regulate the flow of code execution based on whether specific conditions evaluate to true or false.

These conditional operators are fundamental for implementing conditional rendering or decision-based logic in Javascript.

if…else

We can render distinct JSX elements and components conditionally using the if-else expression. Note that while we can wrap a JSX element within an if-else block, we cannot write an if-else statement within a JSX element.

As we will see in the next section, using a ternary operator is a better option if we want to render a conditional operator within the syntax of a JSX element.

In the example below, the if-else statements display a login button for users who are not signed in and a logout button for those who are.

Source code:

import { useState } from "react";
import PropTypes from "prop-types";

const AuthenticationButton = ({ isLoggedIn, setIsLoggedIn }) => {
  if (isLoggedIn) {
    return (
      <button
        style={{
          background: "red",
          color: "white",
          borderRadius: "5px",
          padding: "6px 12px",
          border: "none",
          outline: "none",
        }}
        onClick={() => setIsLoggedIn((prevLoginStatus) => !prevLoginStatus)}
      >
        Logout
      </button>
    );
  }
  return (
    <button
      style={{
        background: "dodgerblue",
        color: "white",
        borderRadius: "5px",
        padding: "6px 12px",
        border: "none",
        outline: "none",
      }}
      onClick={() => setIsLoggedIn((prevLoginStatus) => !prevLoginStatus)}
    >
      Login
    </button>
  );
};

AuthenticationButton.propTypes = {
  isLoggedIn: PropTypes.bool.isRequired,
  setIsLoggedIn: PropTypes.func.isRequired,
};

const Page = () => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  return (
    <section
      style={{
        background: "white",
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        minHeight: "100vh",
        width: "100vw",
      }}
    >
      <AuthenticationButton
        isLoggedIn={isLoggedIn}
        setIsLoggedIn={setIsLoggedIn}
      />
    </section>
  );
};

export default Page;

In the Page component above, the <AuthenticationButton /> component accepts a isLoggedIn prop, which is a type of boolean (true or false), representing the user’s authentication status. This status updates using the setIsLoggedIn function.

The <AuthenticationButton /> component uses a if-else statement to render the buttons conditionally.

It returns a “Logout” button if the user is logged in (isLoggedIn is true); otherwise, it returns a “Login” button.

This example logic encapsulates the decision-making process based on the user’s authentication status, illustrating the simplicity and effectiveness of conditional rendering in React components.

Conditional (Ternary) Operator

The Ternary Operator is another way to write conditional statements in JavaScript. It provides a shorthand syntax for an if-else statement, allowing you to write conditional expressions easily in a single line.

Below is the syntax for the ternary operator.

condition ? ifBlock : elseBlock

Therefore, if the condition before the question mark evaluates to true, the ifBlock renders, otherwise the elseBlock will render.

This syntax enhances readability and best in situations when the conditions and outcomes are simple, making it a versatile tool for writing efficient and clean code in React.

Scenario

Let’s consider a scenario where you want to render a different message depending on whether a user is a subscriber to a newsletter in a React component. The ternary operator can handle this condition.

Case 1: We render the text “Thank you for subscribing!” if the user is a subscriber to the newsletter i.e variable isSubscribed is true.

Case 2: We render the text “Subscribe now for the latest updates!” if the user is not a subscriber i.e variable isSubscribed is false.

Demo:

Depending on the value of isSubscribed, the component conditionally renders different messages and content using the ternary operator.

It’ll show information about the newsletter and a thank-you message if the user is a subscriber (isSubscribed is true), with a button to unsubscribe.

If not (isSubscribed is false), it notifies the user to subscribe to receive the most recent information, with a button subscribe.

This demonstrates how React’s ternary operator can handle conditional rendering, producing a readable code.

Source code:

import { useState } from "react";
import PropTypes from "prop-types";

const NewsletterWidget = ({ isSubscribed, setIsUserSubscribed }) => {
  return (
    <div>
      <h2 style={{ color: "#334155", fontWeight: "600" }}>
        {isSubscribed
          ? "Thank you for subscribing!"
          : "Subscribe now for the latest updates!"}
      </h2>
      <p style={{ color: "#64748b", fontWeight: "500" }}>
        {isSubscribed
          ? "You will receive our newsletter with exciting content and updates."
          : "Don’t miss out! Subscribe to get the latest news and updates delivered to your inbox."}
      </p>
      <button
        onClick={() =>
          setIsUserSubscribed(
            (prevSubscriptionStatus) => !prevSubscriptionStatus
          )
        }
      >
        {isSubscribed ? "Unsubscribe πŸ™" : "Subscribe πŸ˜ƒ"}
      </button>
    </div>
  );
};

NewsletterWidget.propTypes = {
  isSubscribed: PropTypes.bool.isRequired,
  setIsUserSubscribed: PropTypes.func.isRequired,
};

const Page = () => {
  const [userIsSubscribed, setIsUserSubscribed] = useState(false);

  return (
    <section
      style={{
        background: "white",
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        textAlign: "center",
        padding: "12px",
      }}
    >
      <h1 style={{ color: "#0f172a", fontWeight: "700" }}>
        Welcome to our Newsletter
      </h1>
      <NewsletterWidget
        isSubscribed={userIsSubscribed}
        setIsUserSubscribed={setIsUserSubscribed}
      />
    </section>
  );
};

export default Page;

Logical Operators (Short Circuit Evaluation)

In JavaScript, logical operators are used on boolean values to perform logical operations.

These operators display a behavior known as “short-circuit evaluation,” whereby the evaluated value of the first operand determines the behavior of the second operand. As a result, the outcome of the first operand determines whether or not the second operation evaluates.

In this section, we will examine the two common logical operators that facilitate short-circuit evaluation in JavaScript: The Logical AND (&&) and The Logical OR (||) operators.

The AND (&&) Operator

The && operator returns true if both the left and right operands are true.

const result = true && (3 > 1); 
console.log(result) // Evaluates to true

In the example above, the result variable returns true because the left operand is true and the right operand is (3 > 1) which also evaluates to true.

The AND (&&) Operator Short-circuit Evaluation Table

TermDescription
OperatorThe AND (&&) operator
Short-circuit evaluationIf the first operand is false, the second operand is not evaluated, resulting in a false overall outcome.
The right operand is evaluated only if the left operand is true.
Example 1true && true evaluates to true.
Example 2false && true evaluates to false without evaluating the second operand.
Example 3false && anything evaluates to false without evaluating the second operand.
Example 4true && false evaluates to false without evaluating the second operand.
Example 5anything && true evaluates to the value of the second operand.
Example 6anything && anything evaluates to true if both operands are true, otherwise false.

Scenario:

We want to implement conditional rendering to display a “Loading… Please wait” text when the page is loading and reveal the “Page is ready πŸš€” text when the page is done loading.

Demo:

Source code:

import { useEffect, useState } from "react";

const PageLoader = () => {
  return <p>Loading... Please wait</p>;
};

const Page = () => {
  const [isPageLoading, setIsPageLoading] = useState(true);

  useEffect(() => {
    setTimeout(() => {
      setIsPageLoading(false);
    }, 3000);
  }, []);

  return (
    <section
      style={{
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        minHeight: "100vh",
      }}
    >
      {isPageLoading && <PageLoader isLoading={isPageLoading} />}
      {!isPageLoading && <p>Page is ready πŸš€</p>}
    </section>
  );
};

export default Page;

From the code above, the PageLoader component renders if the isPageLoading state is true, and when it’s false, we’re going to render the Page is ready πŸš€ text.

The OR (||) Operator

The || operator returns true if at least one operand is true and it returns false if any of the operands is false.

Code Example:

const result = true || (3 > 1); 
console.log(result) // Evaluates to true

const result = false || (3 > 1); 
console.log(result) // Evaluates to false

const result = false || false; 
console.log(result) // Evaluates to true

From the code above:

  • The first result variable returns true because both the left and right operands are equal to true.

  • The second result variable returns false because the left operand is false.

  • The third result variable returns false because both operands are false.

The OR (||) Operator Short-circuit Evaluation Table

TermDescription
OperatorThe OR operator
Short-circuit evaluationIf the first operand is true, the second operand is not evaluated, resulting in a true overall outcome.
The right operand is evaluated only if the left operand is false.

Example 1:

true || true evaluates to true without evaluating the second operand.

Example 2:

false || true evaluates to true.

Example 3:

true || anything evaluates to true without evaluating the second operand.

Example 4:

false || false evaluates to false without evaluating the second operand.

Example 5:

anything || true evaluates to true without evaluating the second operand.

Example 6:

anything || anything evaluates to true if at least one operand is true, otherwise false.

Scenario:

We aim to retrieve the username from local storage. If the username does not exist, we intend to display the string ‘Guest’ using the Logical OR (||) operator.

Demo:

Source code:

import React from "react";

const UserProfile = () => {
  // Fetch state from local storage
  const storedUsername = localStorage.getItem("username");

  return (
    <div>
      <h1>Welcome, {storedUsername || "Guest"}!</h1>
      {/* Rest of the component */}
    </div>
  );
};

function App() {
  return (
    <div>
      <UserProfile />
    </div>
  );
}

export default App;

From the code above; the CurrentUserName component dynamically renders the username fetched from local storage, displaying “Guest” if no username exists.

It also provides functionality to log in and log out by manipulating the “username” item in local storage.

Switch Statement

A switch statement is a control flow statement that provides an efficient way to handle multiple conditions based on the value of an expression.

A switch statement usually has the following syntax:

switch (expression) {
  case value1:
    // this line executes if expression equals value1
    break;
  case value2:
    // this line executes if expression equals value2
    break;
  // ... more cases
  default:
    // this line executes if expression doesn't match any case
}
Syntax/keywordDescription
expressionThis is the main value that is compared to the different cases.
caseEach case represents a possible value that might match the expression.
breakThis terminates the switch statement and prevents fall-through to the next case.
defaultIf none of the cases match the expression, the code inside the default block will be executed. The default block is optional.

Scenario:

Generate distinct messages based on the specific day of the week, as illustrated below.

Demo:

Source code:

import PropTypes from "prop-types";

const MessageOfTheDay = ({ weekDay }) => {
  let message;
  const lowerCaseWeekDay = weekDay.toLowerCase();

  switch (lowerCaseWeekDay) {
    case "monday":
      message = "This is the second day of the week";
      break;
    case "friday":
      message = "This is the sixth day of the week";
      break;
    case "sunday":
      message = "This is the first day of the week";
      break;
    default:
      message = "Invalid day of the week";
  }

  return <h1>{message}</h1>;
};

MessageOfTheDay.propTypes = {
  weekDay: PropTypes.oneOf([
    "monday",
    "tuesday",
    "wednesday",
    "thursday",
    "friday",
    "saturday",
  ]),
};

const Page = () => {
  return (
    <section>
      <MessageOfTheDay weekDay='Sunday' />
      <MessageOfTheDay weekDay='Monday' />
      <MessageOfTheDay weekDay='Friday' />
      <MessageOfTheDay weekDay='January' />
    </section>
  );
};

export default Page;

Enum Objects (Mapping)

An enum facilitates multiple conditional renderings in an easily understandable way. In React we can create an object with key-value pairs and use it as an enum.

Below is the basic syntax of Enum Objects.

const enum = {
    key: value,
};

While React doesn’t have native enums, plain JavaScript objects can simulate them for conditional rendering.

Scenario:

We want to dynamically render a specific tier component based on the value of the selected tier number using an Enum Object.

Demo:

This component allows users to select a tier number from a dropdown menu, dynamically rendering the corresponding tier component based on the selected number. If no tier is selected, it displays a message indicating the absence of selection.

Source code:

import { useState } from "react";

// Tier 1 component
const Tier1Component = () => {
  return <h2>Tier 1 Component</h2>;
};

// Tier 2 component
const Tier2Component = () => {
  return <h2>Tier 2 Component</h2>;
};

// Tier 3 component
const Tier3Component = () => {
  return <h2>Tier 3 Component</h2>;
};

// Enum Object
const mapTierNumberToComponent = {
  1: Tier1Component,
  2: Tier2Component,
  3: Tier3Component,
};

const Page = () => {
  const [selectedTierNumber, setSelectedTierNumber] = useState(null);
  const RenderedTier = mapTierNumberToComponent[selectedTierNumber];
  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
      }}
    >
      {selectedTierNumber ? <RenderedTier /> : <h2>No tier selected</h2>}
      <select onChange={(e) => setSelectedTierNumber(e.target.value)}>
        <option value=''>None</option>
        <option value='1'>1</option>
        <option value='2'>2</option>
        <option value='3'>3</option>
      </select>
    </div>
  );
};

export default Page;

The enum object is quite helpful because it allows us to easily increase the number of tiers by adding new tiers to the mapTierNumberToComponent variable.

If we were to use a ternary operator in this case, managing an increase in tier options would be challenging.

Immediately invoked function expressions (IIFE)

An Immediately Invoked Function Expression (IIFE) is a JavaScript design pattern where a function defines and executes immediately after its creation.

It’s a way to encapsulate code and create a private scope for variables, preventing them from polluting the global scope.

Below is the syntax of the Immediately Invoked Function Expression(IIFE)

(function() {
  // Block of code to be executed immediately
})();

Source code:

import { useEffect, useState } from "react";

const CounterComponent = () => {
  const [counter, setCounter] = useState(0);

  useEffect(() => {
    // IIFE
    (function () {
      // This block of code is executed immediately after the component mounts
      console.log("IIFE executed");
      setCounter((prevCounter) => prevCounter + 1);
    })();
  }, []);
  return <h1>Counter: {counter}</h1>;
};

const Page = () => {
  return <CounterComponent />;
};

export default Page;

The CounterComponent utilizes the useEffect hook to execute a block of code immediately after the component mounts.

This block of code increments the counter state using the useState hook. The Page component renders the CounterComponent, resulting in the display of a counter that increments by 1 every time the component mounts.

What can be Conditionally Rendered in React?

Conditional rendering in React lets you display or hide items or components according to specific criteria. Almost anything can conditionally render inside a React component.

The following are some typical React use cases for conditional rendering:

  • Components: Different components can be rendered conditionally depending on a prop or state. For instance, displaying a loading spinner to indicate the progress of data retrieval or displaying distinct areas of a form contingent on user input.

    {isLoading ? <LoadingSpinner /> : <DataComponent />}
  • HTML Elements: It is possible to render JSX components or text conditionally according to a condition. For example, indicating to the user if they are signed in or not.

    {isLoggedIn ? <p>Welcome back!</p> : <p>Please log in to continue.</p>}
  • Styles and Classes: You can conditionally apply styles or classes to elements based on certain conditions.

    <div className={isError ? 'error' : 'info'}>
      {isError ? 'Error occurred!' : 'Welcome'}
    </div>
  • Routes: In the context of React Router, you can conditionally render different components or routes based on the current route or other conditions.

    <Routes>
        <Route
         path="/"
         element={isLoggedIn ? <Home /> : <Login />}
        />
    </Routes>

To learn more about conditional rendering in React, you can check out the video tutorial below:

React Conditional Rendering Use Cases

Here are some key use cases of conditional rendering in React.

UsecaseDescription
Authentication and AuthorizationConditional rendering allows us to select which components to render or which routes to send users to depending on whether or not they are signed in.
Loading StatesWhen an API call is performed, it may take a few seconds to receive a response. Until the necessary data is received and shown on the interface, the loading spinner may be displayed with the help of conditional rendering.
Error HandlingDepending on whether data fetching is successful or there are errors, conditional rendering can be used to render alternate content. In addition, we can display error messages or retry buttons based on our desire to attempt the API call again.
Conditional StylesAn element can be given a particular style or CSS class depending on specific conditions. For example, we can display the color green in the event of a success and red in the event of an error.
Role-Based ViewsDifferent roles can be assigned to users of an application (e.g., admin, customer, etc.), and conditional rendering can be used to determine which module a user should view depending on their role.
Rendering Components based on StateAdditionally, distinct components can be displayed according to any other application state, which can include everything from asynchronous data fetching to the on/off state of a radio button.
Dynamic FormCertain fields can be shown or hidden using conditional rendering in response to user input or selected options. We can also choose to enable or disable the submit button depending on input validation.

Routes Conditional Rendering

React offers several ways to conditionally render routes based on different criteria, like roles, user types, and countries. This can be achieved through route matching and rendering specific components when certain conditions are met.

Based on role

Scenario:

When users log in to our system, they come with different roles depending on whether they are admin or regular users. We can define different routes depending on this role.

Source code:

Here, we are rendering either the <AdminDashboard /> or <UserDashboard /> depending on the role of the user.

import { Routes, Route, Navigate } from 'react-router-dom';
// User data retrieved after logging in
const user = { role: "admin" }; 

function App() {
  return (
    <Routes>
      <Route
        path="/dashboard"
        element={
          user.role === "admin" ? (
            <AdminDashboard />
          ) : (
            <UserDashboard />
          )
        }
      />

      {/*We can handle for Other routes here */}
    </Routes>
  );
}

User type

Scenario:

Like user roles, we can have users with several tiers, such as tier 1, 2, and 3, etc., and we may want to provide them with different experiences according to their tier.

We can route users to different URLs or pages according to their tiers.

Source code:

Here, we are rendering either the <Tier1Home /> or <Tier2Home /> depending on the tier of the user.

// Logged in user tier
const user = { type: tier1 }; 

function App() {
  return (
    <Routes>
      <Route
        path="/tier1"
        element={
          user.type === 'tier1' ? (
            <Tier1Home />
          ) : (
            <RegularHome />
          )
        }
      />
      <Route
        path="/tier2"
        element={
          user.type === 'tier2' ? (
            <Tier2Home />
          ) : (
            <Navigate to="/" />
          )
        }
      />
      {/* We can handle for Other routes here */}
    </Routes>
  );
}

Country

Scenario:

We can decide to provide customers with distinct experiences according to the country in which they happen to be. Based on their IP address or the information gathered during their registration on the website, we are able to determine the user’s location. From there, we can utilize that information to route them to various areas inside our application.

Source code:

Here, we are rendering either the <USDashboard /> or <GeneralDashboard /> depending on the country of the user.

// C ountry of logged in user
const user = { country: 'US' }; 

function App() {
  return (
    <Routes>
      <Route
        path="/"
        element={
          user.country === 'US' ? (
            <USDashboard />
          ) : (
            <GeneralDashboard />
          )
        }
      />
      {/* We can handle for Other routes here */}
    </Routes>
  );
}

Component Conditional Rendering

React allows developers to create dynamic applications, and components are the essential building blocks of a React application. Various conditional operators, such as ternary, if-else, and logical operators, are essential to rendering these components dynamically.

Demo:

The example below shows how to toggle a button to cause the error or success component to be rendered dynamically.

Source code:

import { useState } from "react";

const SuccessMessage = () => {
  return (
    <div>
      <h1>This is a Success component </h1>
      <p>Great job! You&apos;ve succeeded 🟒</p>
    </div>
  );
};

const ErrorMessage = () => {
  return (
    <div>
      <h1>This is an Error component</h1>
      <p>Uh-oh! Something went wrong πŸ”΄</p>
    </div>
  );
};

const Page = () => {
  const [showSuccess, setShowSuccess] = useState(false);

  const toggleMessage = () => {
    setShowSuccess((prevState) => !prevState);
  };

  return (
    <div>
      <button onClick={toggleMessage}>
        Toggle Message ({showSuccess ? "Error" : "Success"})
      </button>
      {showSuccess ? <SuccessMessage /> : <ErrorMessage />}
    </div>
  );
};

export default Page;

The App component includes a button that toggles between success and error message component. The toggleMessage function is triggered by the button click event, which updates the showSuccess state, dynamically changing the component being displayed.

JSX Elements Conditional Rendering

JSX stands for JavaScript XML. JSX is a special kind of JavaScript code that makes it easier for developers to create user interfaces with React by using a syntax that looks a lot like writing HTML.

The same conditional rendering logic that was previously demonstrated for component conditional rendering can be used to render JSX items conditionally in React.

Now let’s look at an example in which we conditionally render different headings based on a boolean variable.

When an admin logs in, we render a different JSX element than when a user signs in, as seen in the image below.

Source code:

function Page() {
  const userRole = "admin";

  return (
    <div>
      {userRole === "admin" ? (
        <div>
          <h1>Welcome, Admin!</h1>
          <p>You have access to all advanced features.</p>
        </div>
      ) : (
        <div>
          <h1>Welcome, User!</h1>
          <p>Enjoy a great user experience.</p>
        </div>
      )}
    </div>
  );
}

export default Page;

In this example, the JSX elements within the div are conditionally rendered based on the value of userRole.

If the userRole is ‘admin’, it renders a special welcome message for administrators with access to all advanced features. Otherwise, it renders a generic welcome message for regular users.

This shows that you can conditionally render different JSX elements to improve the user experience in our applications.

Best Practices

When working with conditional rendering in React, several best practices can help improve code readability and maintainability. Here are some recommendations:

Best Practices for Conditional Rendering in React

Select the most appropriate approach or render method based on complexity. For simple cases, consider if/else or ternary operators. For multiple distinct cases, switch statements can be suitable.

Break down complex conditional rendering into smaller, reusable components for cleaner code and organization.

Keep your conditional structures flat and avoid deeply nested if/else statements or switch cases to improve performance and readability (Avoid excessive nesting)

For more complex conditions or logic, encapsulate the rendering logic in a separate function or variable. This enhances readability.

Use the logical AND (&&) operator when rendering components based on simple conditions. This is concise and avoids unnecessary wrapping elements.

In summary, conditional rendering is a very useful technique in React, but it should not be used improperly to avoid potential problems that can make your code unreadable.

For clearer code, choose the appropriate conditional rendering method based on complexity (if/else, ternary, or switch), break down complex rendering into reusable components, avoid deep nesting, and use the logical AND (&&) for simplicity.

Wrapping Up Conditional Rendering in React

This guide has covered the essentials of React conditional rendering, from the basics to practical tips, shed light on key concepts, explored diverse use cases, and outlined valuable best practices.

We can hardly build a substantial application without making use of conditional rendering, so it is a valuable tool to have in your toolkit to create more efficient and high-performing applications.

By applying these concepts and practices, you’ll be better positioned to create dynamic and user-friendly interfaces.

Happy coding! πŸŽ‰

Checkout Purecode!

I recommend you try out Purecode, an AI tool that can generate custom HTML, CSS, and JavaScript components. Here are some of its features:

  • It uses an AI assistant to generate thousands of responsive pre-made components for you.
  • The components come with default styling using CSS, Tailwind CSS, or your own custom styles so you can match your brand’s design.
  • You can easily customize the generated components to suit your specific needs – change colors, spacing, paddings, margins, etc.
  • It generates both the HTML markup and CSS styles for the components, saving you development time.

It also includes some JavaScript functionality within the components to make them interactive

Ayodele Samuel Adebayo

Ayodele Samuel Adebayo