Dev.to WebDev 🛠 Dev 👁 0 📖 4 min read

React Mastery Series – Day 10: Conditional Rendering in React – Building Dynamic User Interfaces

Welcome back to the React Mastery Series! In the previous article, we explored Event Handling in React and learned how applications respond to user interactions such as clicks, typing, and form submissions. Today, we w

Welcome back to the React Mastery Series!

In the previous article, we explored Event Handling in React and learned how applications respond to user interactions such as clicks, typing, and form submissions.

Today, we will learn another core React concept that is used in almost every real-world application:

Conditional Rendering

Modern applications rarely display the same UI to every user.

A banking application may show:

  • Login page for unauthenticated users
  • Dashboard for logged-in users
  • Admin features for administrators
  • Different screens based on account status

An e-commerce application may show:

  • Products when data exists
  • Loading indicators while fetching data
  • Error messages when API calls fail
  • Empty states when no results are found

React handles these scenarios using conditional rendering.

What is Conditional Rendering?

Conditional rendering means displaying different UI elements based on certain conditions.

The concept is simple:

Condition is true
        |
        ↓
Render UI A


Condition is false
        |
        ↓
Render UI B

In React, conditions are written using normal JavaScript.

Conditional Rendering Using if/else

The simplest approach is using JavaScript if/else.

Example:

function LoginStatus() {

  const isLoggedIn = true;

  if (isLoggedIn) {
    return <h1>Welcome Back!</h1>;
  }

  return <h1>Please Login</h1>;

}

If:

isLoggedIn = true;

Output:

<h1>Welcome Back!</h1>

If:

isLoggedIn = false;

Output:

<h1>Please Login</h1>

The JSX returned by the component is converted by React into actual DOM elements during rendering.

Conditional Rendering Using Variables

Sometimes, conditions can become more readable by storing the UI in a variable.

Example:

function Dashboard() {

  const isAdmin = true;

  let content;

  if (isAdmin) {
    content = <AdminPanel />;
  } else {
    content = <UserPanel />;
  }

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

}

This approach is useful when the UI logic becomes more complex.

Conditional Rendering Using Ternary Operator

The ternary operator is one of the most commonly used patterns in React.

Syntax:

condition ? trueValue : falseValue

Example:

function Profile() {

  const isLoggedIn = true;

  return (
    <h2>
      {
        isLoggedIn
          ? "My Profile"
          : "Login"
      }
    </h2>
  );

}

Output:

My Profile

Real-World Example: Authentication

Most enterprise applications have authentication-based rendering.

Example:

function Header() {

  return (
    <header>
      {
        isAuthenticated
          ? <UserMenu />
          : <LoginButton />
      }
    </header>
  );

}

Flow:

User Logged In
       |
       ↓
Show Profile Menu


User Logged Out
       |
       ↓
Show Login Button

Logical AND (&&) Rendering

When you want to render something only when a condition is true, use the logical AND operator.

Example:

function Notifications() {

  const hasNotifications = true;

  return (
    <div>
      {
        hasNotifications &&
        <NotificationList />
      }
    </div>
  );

}

Meaning:

Condition is true
        |
        ↓
Render Component

Condition is false
        |
        ↓
Render Nothing

Handling Loading States

API-driven applications usually have multiple states:

Loading
   |
   ↓
Success
   |
   ↓
Display Data

Example:

function Users() {

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

  return <UserList />;

}

This pattern is common in:

  • Dashboards
  • Banking applications
  • E-commerce websites
  • Admin portals

Rendering Error Messages

Applications must handle failures gracefully.

Example:

function PaymentStatus() {

  return (
    <div>
      {
        error
          ? <p>Payment Failed</p>
          : <p>Payment Successful</p>
      }
    </div>
  );

}

Multiple Conditions

Production applications often have multiple UI states.

Example:

function OrderStatus() {

  if (status === "loading") {
    return <Loading />;
  }

  if (status === "success") {
    return <OrderDetails />;
  }

  if (status === "error") {
    return <ErrorMessage />;
  }

}

This is often cleaner than deeply nested ternary operators.

Avoid Complex Nested Ternaries

Example:

{
  isLoggedIn
    ? isAdmin
      ? <Admin />
      : <User />
    : <Login />
}

Although valid, this quickly becomes difficult to maintain.

A cleaner approach:

function ApplicationContent() {

  if (!isLoggedIn) {
    return <Login />;
  }

  if (isAdmin) {
    return <Admin />;
  }

  return <User />;

}

Readable code is easier to debug and maintain.

Conditional Styling

Sometimes we don't change the component, but only its style.

Example:

<button
  className={
    isActive
      ? "active"
      : "inactive"
  }
>
  Save
</button>

Common use cases:

  • Active navigation links
  • Selected tabs
  • Disabled buttons
  • Validation messages

Conditional Rendering vs CSS Hiding

There is an important difference.

Conditional Rendering

{
  showComponent && <Component />
}

The component is not created when the condition is false.

CSS Hiding

.hidden {
  display: none;
}

The component still exists but is hidden visually.

Choose the approach depending on your requirement.

Real-World Example: Banking Dashboard

Consider a retail banking application:

Check Authentication
          |
          |
          ├── Not Authenticated
          |          |
          |          ↓
          |       Login Page
          |
          └── Authenticated
                     |
                     ↓
              Dashboard
                     |
                     ↓
          Check Account Status
                     |
          ┌──────────┴──────────┐
          ↓                     ↓
    Active Account        Blocked Account
          ↓                     ↓
 Account Details       Contact Support

Conditional rendering controls the entire user experience.

Rendering Empty States

A common production pattern:

function Products() {

  return (
    <div>
      {
        products.length > 0
          ? <ProductList />
          : <EmptyState />
      }
    </div>
  );

}

Used in:

  • Transaction history
  • Shopping carts
  • Search results
  • Notifications

Common Mistakes

Mistake 1: Incorrect Logical AND Condition

Avoid:

{
  items.length && <List />
}

If the array is empty, React may render:

0

Better:

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

Mistake 2: Too Much Logic Inside JSX

Avoid writing complex conditions directly inside JSX.

Instead:

const shouldShowAdmin =
  user.role === "ADMIN";

Then:

{
  shouldShowAdmin && <AdminPanel />
}

Mistake 3: Duplicating UI

Avoid:

condition
?
<div>Same Content</div>
:
<div>Same Content</div>

Extract reusable components instead.

Best Practices

  • Keep conditions simple.
  • Prefer early returns for complex scenarios.
  • Avoid deeply nested ternary operators.
  • Handle loading, error, and empty states explicitly.
  • Separate business logic from JSX.
  • Create reusable components for different UI states.

Key Takeaways

Today, we learned:

✅ Conditional rendering allows dynamic UI changes.
✅ React uses normal JavaScript conditions.
✅ if/else, ternary operators, and && are common patterns.
✅ Authentication, loading, and error states rely heavily on conditional rendering.
✅ Clean conditional logic improves maintainability.

Coming Next 🚀

In Day 11, we will explore:

Rendering Lists in React – Working with Arrays and Keys

We will learn:

  • Rendering arrays using map()
  • Understanding the key prop
  • Why keys are important
  • Common key mistakes
  • Dynamic tables and lists
  • Real-world examples

Lists are everywhere in modern applications:

  • Transaction history
  • Product catalogs
  • User management tables
  • Notifications

Mastering list rendering is essential for every React developer.

Happy Coding! 🚀

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.