DEV Community

Cover image for React Mastery Series – Day 10: Conditional Rendering in React – Building Dynamic User Interfaces
Siva Samanthapudi
Siva Samanthapudi

Posted on

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 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
Enter fullscreen mode Exit fullscreen mode

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>;

}
Enter fullscreen mode Exit fullscreen mode

If:

isLoggedIn = true;
Enter fullscreen mode Exit fullscreen mode

Output:

<h1>Welcome Back!</h1>
Enter fullscreen mode Exit fullscreen mode

If:

isLoggedIn = false;
Enter fullscreen mode Exit fullscreen mode

Output:

<h1>Please Login</h1>
Enter fullscreen mode Exit fullscreen mode

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>
  );

}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Example:

function Profile() {

  const isLoggedIn = true;

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

}
Enter fullscreen mode Exit fullscreen mode

Output:

My Profile
Enter fullscreen mode Exit fullscreen mode

Real-World Example: Authentication

Most enterprise applications have authentication-based rendering.

Example:

function Header() {

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

}
Enter fullscreen mode Exit fullscreen mode

Flow:

User Logged In
       |
       ↓
Show Profile Menu


User Logged Out
       |
       ↓
Show Login Button
Enter fullscreen mode Exit fullscreen mode

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>
  );

}
Enter fullscreen mode Exit fullscreen mode

Meaning:

Condition is true
        |
        ↓
Render Component

Condition is false
        |
        ↓
Render Nothing
Enter fullscreen mode Exit fullscreen mode

Handling Loading States

API-driven applications usually have multiple states:

Loading
   |
   ↓
Success
   |
   ↓
Display Data
Enter fullscreen mode Exit fullscreen mode

Example:

function Users() {

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

  return <UserList />;

}
Enter fullscreen mode Exit fullscreen mode

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>
  );

}
Enter fullscreen mode Exit fullscreen mode

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 />;
  }

}
Enter fullscreen mode Exit fullscreen mode

This is often cleaner than deeply nested ternary operators.


Avoid Complex Nested Ternaries

Example:

{
  isLoggedIn
    ? isAdmin
      ? <Admin />
      : <User />
    : <Login />
}
Enter fullscreen mode Exit fullscreen mode

Although valid, this quickly becomes difficult to maintain.

A cleaner approach:

function ApplicationContent() {

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

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

  return <User />;

}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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 />
}
Enter fullscreen mode Exit fullscreen mode

The component is not created when the condition is false.


CSS Hiding

.hidden {
  display: none;
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Conditional rendering controls the entire user experience.


Rendering Empty States

A common production pattern:

function Products() {

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

}
Enter fullscreen mode Exit fullscreen mode

Used in:

  • Transaction history
  • Shopping carts
  • Search results
  • Notifications

Common Mistakes

Mistake 1: Incorrect Logical AND Condition

Avoid:

{
  items.length && <List />
}
Enter fullscreen mode Exit fullscreen mode

If the array is empty, React may render:

0
Enter fullscreen mode Exit fullscreen mode

Better:

{
  items.length > 0 && <List />
}
Enter fullscreen mode Exit fullscreen mode

Mistake 2: Too Much Logic Inside JSX

Avoid writing complex conditions directly inside JSX.

Instead:

const shouldShowAdmin =
  user.role === "ADMIN";
Enter fullscreen mode Exit fullscreen mode

Then:

{
  shouldShowAdmin && <AdminPanel />
}
Enter fullscreen mode Exit fullscreen mode

Mistake 3: Duplicating UI

Avoid:

condition
?
<div>Same Content</div>
:
<div>Same Content</div>
Enter fullscreen mode Exit fullscreen mode

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! 🚀

Top comments (0)