Paramclasses Academy - Blog

Tutorials Details

←
Post 10 of 29
→

What is Conditional Rendering in React — Displaying UI Based on Conditions ?

What is Conditional Rendering in React — Displaying UI Based on Conditions ?

October 29, 2026

1. Introduction

Conditional Rendering is an important concept in React.js that allows developers to display different UI elements based on specific conditions.

In real-world applications, the interface frequently changes according to user actions, application state, authentication status, and data availability.

For example:

  • Display a Login button when a user is logged out.

  • Display a Dashboard when a user is logged in.

  • Show a loading message while fetching API data.

  • Display an error message when an operation fails.

  • Show a success message after submitting a form.

React uses standard JavaScript conditions and expressions to control which elements appear on the screen.

By the end of this tutorial, you will understand how to implement conditional rendering using if/else, the ternary operator, logical AND (&&), and early returns.

2. Learning Objectives

After completing this tutorial, you will be able to:

  1. Understand conditional rendering in React.

  2. Use if/else statements to determine what a component returns.

  3. Apply the ternary operator inside JSX.

  4. Use logical AND (&&) to conditionally display elements.

  5. Implement early returns for simpler component logic.

  6. Show and hide UI elements using React state.

  7. Build loading, error, success, and authentication-related interfaces.

  8. Avoid common conditional-rendering mistakes.

3. Core Concepts and Explanation

3.1 What Is Conditional Rendering?

Conditional rendering means displaying UI elements only when specified conditions are satisfied.

Consider this JavaScript example:

const isLoggedIn = true;

if (isLoggedIn) {
  console.log("Welcome back!");
} else {
  console.log("Please log in.");
}

In React, the same condition can determine which JSX element is returned.

function Welcome() {
  const isLoggedIn = true;

  if (isLoggedIn) {
    return <h2>Welcome back!</h2>;
  }

  return <h2>Please log in.</h2>;
}

export default Welcome;

Explanation:

  • isLoggedIn stores a Boolean value.

  • If its value is true, React renders the welcome message.

  • If its value is false, React renders the login message.

  • Only the selected JSX output is rendered by this component.

3.2 Conditional Rendering Using if/else

Use if/else when you need to choose between different blocks of UI or when the logic contains multiple statements.

function UserStatus() {
  const isLoggedIn = false;

  let message;

  if (isLoggedIn) {
    message = <h2>You are logged in.</h2>;
  } else {
    message = <h2>Please log in to continue.</h2>;
  }

  return (
    <div>
      {message}
    </div>
  );
}

export default UserStatus;

How it works:

  1. The component checks the value of isLoggedIn.

  2. It assigns the appropriate JSX to message.

  3. JSX expressions use curly braces {} to display the value.

  4. React renders the selected message.

Important: You cannot directly place a normal if/else statement inside JSX curly braces. Use it before the return statement, or use a conditional expression such as the ternary operator.

3.3 Conditional Rendering Using the Ternary Operator

The ternary operator is a concise way to choose between two expressions.

Syntax:

condition ? expressionIfTrue : expressionIfFalse

React example:

function LoginStatus() {
  const isLoggedIn = true;

  return (
    <div>
      {isLoggedIn
        ? <h2>Welcome back!</h2>
        : <h2>Please log in.</h2>
      }
    </div>
  );
}

export default LoginStatus;

Explanation:

  • If isLoggedIn is true, the first message appears.

  • If it is false, the second message appears.

  • The ternary expression can be used directly inside JSX.

You can also conditionally change button text:

function LoginButton() {
  const isLoggedIn = false;

  return (
    <button>
      {isLoggedIn ? "Logout" : "Login"}
    </button>
  );
}

export default LoginButton;

This example changes the displayed text. It does not yet implement actual login or logout functionality.

Best practice: Use the ternary operator for simple two-way choices. For complex conditions, prefer clearer component logic.

3.4 Conditional Rendering Using Logical AND (&&)

The logical AND operator is useful when an element should appear only if a condition is true.

Syntax:

{condition && <Element />}

Example:

function Notification() {
  const hasNotification = true;

  return (
    <div>
      <h2>Dashboard</h2>

      {hasNotification && (
        <p>You have a new notification!</p>
      )}
    </div>
  );
}

export default Notification;

When hasNotification is true, React displays the notification. When it is false, the notification is omitted.

Important mistake to avoid

Avoid using a number directly on the left side of && when you intend to hide an element.

Incorrect:

function Cart() {
  const itemCount = 0;

  return (
    <div>
      {itemCount && <p>Items in cart</p>}
    </div>
  );
}

When itemCount is 0, JavaScript evaluates the expression to 0. React can render that zero instead of rendering nothing.

Correct:

function Cart() {
  const itemCount = 0;

  return (
    <div>
      {itemCount > 0 && (
        <p>Items in cart: {itemCount}</p>
      )}
    </div>
  );
}

Now the message appears only when the item count is greater than zero.

3.5 Conditional Rendering Using Early Returns

An early return allows a component to return a specific UI before reaching its main output.

This is especially useful for loading states, error states, and missing data.

function Profile() {
  const isLoading = true;

  if (isLoading) {
    return <p>Loading profile...</p>;
  }

  return <h2>Your Profile</h2>;
}

export default Profile;

Since isLoading is true, the component returns the loading message immediately.

A component can also handle multiple states:

function DataStatus() {
  const isLoading = false;
  const hasError = true;

  if (isLoading) {
    return <p>Loading data...</p>;
  }

  if (hasError) {
    return <p>Something went wrong.</p>;
  }

  return <p>Data loaded successfully!</p>;
}

export default DataStatus;

The component checks loading first, then errors, and finally displays the success output when neither condition applies.

3.6 Conditional Rendering Based on React State

In interactive applications, a condition often changes after the user clicks a button or performs another action. The useState Hook allows React to track that change and update the UI.

import { useState } from "react";

function ToggleMessage() {
  const [isVisible, setIsVisible] = useState(false);

  return (
    <div>
      <button onClick={() => setIsVisible(!isVisible)}>
        {isVisible ? "Hide Message" : "Show Message"}
      </button>

      {isVisible && (
        <p>Hello! This message is now visible.</p>
      )}
    </div>
  );
}

export default ToggleMessage;

How it works:

  1. useState(false) initializes isVisible as false.

  2. The button click changes the state to its opposite value.

  3. When isVisible becomes true, the message appears.

  4. When it becomes false, the message disappears.

  5. React automatically updates the rendered UI after the state changes.

This pattern is commonly used for dropdowns, modals, expandable sections, and password-visibility controls.

3.7 Conditional Rendering with Multiple Conditions

Sometimes the UI depends on more than one condition.

function Result() {
  const marks = 75;
  const passingMarks = 40;

  return (
    <div>
      {marks >= passingMarks
        ? <h2>Congratulations! You passed.</h2>
        : <h2>Sorry, you failed.</h2>
      }

      {marks >= 90 && <p>Excellent performance!</p>}
    </div>
  );
}

export default Result;

The first condition determines whether the student passed. The second condition independently displays an additional message for marks of 90 or higher.

For more complex logic, calculate a result before returning JSX instead of creating deeply nested ternary expressions.

4. Practical Code Examples

Example 1: Login and Logout Interface

import { useState } from "react";

function LoginApp() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  return (
    <div>
      <h1>My Application</h1>

      {isLoggedIn ? (
        <div>
          <h2>Welcome to your dashboard!</h2>
          <button onClick={() => setIsLoggedIn(false)}>
            Logout
          </button>
        </div>
      ) : (
        <div>
          <h2>Please log in to continue.</h2>
          <button onClick={() => setIsLoggedIn(true)}>
            Login
          </button>
        </div>
      )}
    </div>
  );
}

export default LoginApp;

What you learn: The interface changes according to the isLoggedIn state. This is a demonstration of conditional UI only; a production application must implement real authentication and server-side authorization.

Example 2: Show and Hide Password

import { useState } from "react";

function PasswordField() {
  const [showPassword, setShowPassword] = useState(false);

  return (
    <div>
      <label htmlFor="password">Password:</label>

      <input
        id="password"
        type={showPassword ? "text" : "password"}
        placeholder="Enter your password"
      />

      <button
        type="button"
        onClick={() => setShowPassword(!showPassword)}
      >
        {showPassword ? "Hide Password" : "Show Password"}
      </button>
    </div>
  );
}

export default PasswordField;

What you learn: A state variable determines both the input type and the button label.

Example 3: Loading, Error, and Success States

import { useState } from "react";

function StatusApp() {
  const [status, setStatus] = useState("loading");

  if (status === "loading") {
    return (
      <div>
        <p>Loading data...</p>
        <button onClick={() => setStatus("success")}>
          Simulate Success
        </button>
        <button onClick={() => setStatus("error")}>
          Simulate Error
        </button>
      </div>
    );
  }

  if (status === "error") {
    return (
      <div>
        <p>Failed to load data.</p>
        <button onClick={() => setStatus("loading")}>
          Try Again
        </button>
      </div>
    );
  }

  return (
    <div>
      <p>Data loaded successfully!</p>
      <button onClick={() => setStatus("loading")}>
        Reload
      </button>
    </div>
  );
}

export default StatusApp;

What you learn: A single state variable can represent multiple UI states. In a real API request, update this state based on the actual request lifecycle rather than simulated button clicks.

Example 4: Conditional Form Validation Message

import { useState } from "react";

function EmailForm() {
  const [email, setEmail] = useState("");
  const [submitted, setSubmitted] = useState(false);

  const isValidEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);

  function handleSubmit(event) {
    event.preventDefault();
    setSubmitted(true);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="email">Email Address:</label>

      <input
        id="email"
        type="email"
        value={email}
        onChange={(event) => {
          setEmail(event.target.value);
          setSubmitted(false);
        }}
        placeholder="Enter your email"
      />

      <button type="submit">Submit</button>

      {submitted && (
        isValidEmail
          ? <p>Email format looks valid.</p>
          : <p>Please enter a valid email address.</p>
      )}
    </form>
  );
}

export default EmailForm;

What you learn: Conditional rendering can display validation feedback only after submission. This simple regex is illustrative, not a complete email-validation system.

5. Real-World Applications

Conditional rendering is used across many types of applications.

E-commerce websites

  • Show an “Add to Cart” button when a product is available.

  • Display “Out of Stock” when inventory is zero.

  • Show a cart count only when items exist.

Admin dashboards

  • Display loading indicators while retrieving statistics.

  • Show an error state when a request fails.

  • Render different navigation options based on the authenticated user's role.

Forms and registration pages

  • Display field-level validation messages.

  • Show a success confirmation after submission.

  • Disable or replace a submit button while a request is processing.

Social media applications

  • Show “Follow” or “Unfollow” based on relationship state.

  • Display notifications when unread items exist.

  • Show an empty-state message when there are no posts.

Security note: Hiding a button or page element is not access control. The backend must verify authentication and permissions for protected data and operations.

6. Common Mistakes and Best Practices

Mistake 1: Using if directly inside JSX

Incorrect:

return (
  <div>
    {if (isLoggedIn) {
      <p>Welcome</p>
    }}
  </div>
);

Correction: Use if/else before the return, or use a ternary expression inside JSX.

Mistake 2: Forgetting the false branch

A ternary expression requires both expressions:

{isLoggedIn ? <p>Welcome</p> : <p>Please log in</p>}

If you only need to show an element when a condition is true, use &&.

Mistake 3: Rendering zero accidentally

Avoid:

{items.length && <ItemList />}

Prefer:

{items.length > 0 && <ItemList />}

Mistake 4: Creating deeply nested ternary expressions

Nested conditions can become difficult to read and maintain. Use early returns or extract a small component when the logic becomes complicated.

Mistake 5: Using state unnecessarily

If a value can be calculated directly from existing props or state, calculate it instead of maintaining duplicate state. Duplicate state can become inconsistent.

Mistake 6: Treating UI conditions as security

A hidden component does not protect data or APIs. Enforce authorization on the server for every protected operation.

Best Practices

  • Use if/else for complex branching.

  • Use ternary expressions for simple two-way choices.

  • Use && when you only need to display an element for a true condition.

  • Use early returns for loading, error, and missing-data states.

  • Keep conditional expressions readable.

  • Test both true and false outcomes.

  • Use meaningful Boolean variable names, such as isLoggedIn, isLoading, and hasError.

7. Practice Exercises

Complete these exercises yourself before checking other solutions.

Exercise 1: Age Verification

Create a component that displays:

  • “You are eligible” if age is 18 or older.

  • “You are not eligible” otherwise.

Exercise 2: Dark Mode Toggle

Create a button that switches between “Enable Dark Mode” and “Disable Dark Mode”. Use useState and conditional rendering to display the current mode.

Exercise 3: Product Availability

Create a product component that shows:

  • “In Stock” when quantity is greater than zero.

  • “Out of Stock” when quantity equals zero.

Exercise 4: Notification Badge

Display a notification message only when the unread notification count is greater than zero. Ensure that zero is not accidentally rendered.

Exercise 5: Form Submission

Build a form that displays a success message after submission and an error message when the input is empty.

Exercise 6: Multi-State Interface

Create a component with three states: loading, error, and success. Use early returns to render the appropriate interface for each state.

8. Key Takeaways and Conclusion

In this tutorial, you learned that conditional rendering controls which elements React displays based on conditions.

Remember these four primary techniques:

  1. if/else: Best for complex branching logic outside JSX.

  2. Ternary operator (? :): Best for choosing between two UI outcomes.

  3. Logical AND (&&): Best for displaying an element only when a condition is true.

  4. Early returns: Best for handling loading, error, and other special states before rendering the main UI.

You also learned how to use useState to dynamically show and hide elements, build login/logout interfaces, display validation messages, and represent different application states.

Mastering conditional rendering will help you build more interactive, maintainable, and user-friendly React applications.

←
Post 10 of 29
→