R

React Handbook

Clean • Professional

React Conditional Rendering

3 minute

Conditional Rendering in React

In React, conditional rendering means showing or hiding elements based on certain conditions — just like using if/else in regular JavaScript, but inside your React components.

It’s one of the most essential concepts for building dynamic, interactive UIs.

What Is Conditional Rendering?

Conditional rendering decides what UI to display depending on the state, props, or logic in your component.

Example:

{isLoggedIn ? <Dashboard /> : <Login />}

Using If Statements (Simple and Readable)

You can use traditional if or if-else statements before the return block in your component.

Example – If/Else Statement

function Greeting({ isLoggedIn }) {
  if (isLoggedIn) {
    return <h2>Welcome back, User!</h2>;
  } else {
    return <h2>Please log in.</h2>;
  }
}

function App() {
  return <Greeting isLoggedIn={true} />;
}
  • The component checks the isLoggedIn prop.
  • Returns one element if true, another if false.
  • You must return one JSX block per condition.

Example – Early Return

This approach keeps your return clean and avoids nested conditions.

function Welcome({ isLoggedIn }) {
  if (!isLoggedIn) {
    return <h2>Access Denied</h2>;
  }

  return <h2>Welcome to the Dashboard!</h2>;
}

Using Ternary Operators – Inline Conditions

Ternary operators are ideal for short, inline decisions inside JSX.

Example – Basic Ternary

function UserStatus({ isOnline }) {
  return <p>{isOnline ? "🟢 Online" : "🔴 Offline"}</p>;
}

Syntax:

condition ? expressionIfTrue : expressionIfFalse

Example – Conditional Component Rendering

function Dashboard({ isAdmin }) {
  return (
    <div>
      <h2>Welcome!</h2>
      {isAdmin ? <button>Admin Settings</button> : <p>Regular User Access</p>}
    </div>
  );
}

Using Logical && (AND) Operator

When you only want to show something if a condition is true, you can use the logical AND (&&) operator.

Example – Show Element Conditionally

  • If message exists, the <p> element renders.
  • If not, React ignores it completely.
function Notification({ message }) {
  return (
    <div>
      <h3>Notifications</h3>
      {message && <p>{message}</p>}
    </div>
  );
}

Example – Combining with State

This is a very common React pattern — toggling content visibility.

import React, { useState } from "react";

function ToggleMessage() {
  const [show, setShow] = useState(false);

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

      {show && <p>Hello, this is a conditional message!</p>}
    </div>
  );
}

Using Logical || (OR) Operator

You can use the OR (||) operator to show a fallback or default element.

Example – Default Value Display

function Welcome({ name }) {
  return <h2>Hello, {name || "Guest"}!</h2>;
}

Conditional Rendering with Multiple Conditions

You can combine all these methods for more complex logic.

Example – Multiple Conditions

function Status({ isLoading, isError }) {
  if (isLoading) return <p>Loading...</p>;
  if (isError) return <p style={{ color: "red" }}>Error occurred!</p>;

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

Conditional Rendering with Fragments

  • Sometimes, you need to show multiple elements conditionally.
  • Use a React Fragment (<>...</>) to wrap them without adding extra DOM nodes.

Example:

function Profile({ isLoggedIn, user }) {
  return (
    <>
      {isLoggedIn ? (
        <>
          <h2>Welcome, {user.name}!</h2>
          <p>Email: {user.email}</p>
        </>
      ) : (
        <p>Please log in to see your profile.</p>
      )}
    </>
  );
}

Combining Conditions with Functions

To keep JSX clean, move conditional logic into helper functions.

Example:

function getStatusMessage(isOnline) {
  return isOnline ? "User is Online" : "User is Offline";
}

function Status({ isOnline }) {
  return <p>{getStatusMessage(isOnline)}</p>;
}

Example – All Techniques Together

import React, { useState } from "react";

function ConditionalExample() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [loading, setLoading] = useState(false);

  if (loading) {
    return <h3>Loading...</h3>;
  }

  return (
    <div>
      <h2>Conditional Rendering Demo</h2>

      {isLoggedIn ? (
        <p>Welcome back, User!</p>
      ) : (
        <p>Please log in to continue.</p>
      )}

      <button onClick={() => setIsLoggedIn(!isLoggedIn)}>
        {isLoggedIn ? "Log Out" : "Log In"}
      </button>
    </div>
  );
}

export default ConditionalExample;

Summary Table

TechniqueSyntax ExampleWhen to Use
If / Elseif (condition) return <A />; else return <B />;Clear branching logic
Ternary Operator{condition ? <A /> : <B />}Inline conditional rendering
Logical AND (&&){condition && <A />}Render something only if true
**Logical OR ( )**
Early Returnif (!data) return null;Avoid unnecessary rendering


Article 0 of 0