← Back to Articles         
Conditional Rendering in React

Conditional Rendering in React

Published on 11 Nov 2026 21 min read React
React Fundamentals

What Is Conditional Rendering in React?

Conditional Rendering in React means displaying different UI elements or components based on a condition.

In simple terms:

If a condition is true, render one UI; if it is false, render another UI.

React uses normal JavaScript expressions to decide what should appear in the UI.

For example:

function Welcome() {
    const isLoggedIn = true;

    return (
        <div>
            {isLoggedIn ? (
                <h2>Welcome, User</h2>
            ) : (
                <h2>Please Login</h2>
            )}
        </div>
    );
}

If isLoggedIn is true:

Welcome, User

If isLoggedIn is false:

Please Login

Conditional rendering is used everywhere in real-world React applications:

  • Show Login / Logout
  • Show Loading indicator
  • Show Error message
  • Show Empty State
  • Show user information
  • Show Admin controls
  • Show different components based on role
  • Show/Hide buttons
  • Show validation messages
  • Show different layouts
  • Render data only when it exists

Why Is Conditional Rendering Required?

A React application rarely displays the same UI all the time.

For example, consider an application with authentication.

When the user is logged in:

Welcome, Syed
Profile
Dashboard
Logout

When the user is not logged in:

Welcome
Login
Register

The React component needs to make a decision:

Is user logged in?
       |
       +---- Yes ----> Show Dashboard
       |
       +---- No -----> Show Login

Conditional rendering allows React to make this decision while rendering the component.


1. Conditional Rendering Using if

The most basic way to implement conditional rendering is using the JavaScript if statement.

However, there is an important point:

You cannot directly use an if statement inside JSX.

This will not work:

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

Instead, perform the condition before the JSX is returned.

function Welcome() {
    const isLoggedIn = true;

    if (isLoggedIn) {
        return <h2>Welcome, User</h2>;
    }

    return <h2>Please Login</h2>;
}

Here React evaluates the condition first.

If:

isLoggedIn === true

React returns:

<h2>Welcome, User</h2>

Otherwise it returns:

<h2>Please Login</h2>

This approach is particularly useful when the two UI branches are substantially different.

if with multiple conditions

function Dashboard({ role }: { role: string }) {

    if (role === "admin") {
        return <h2>Admin Dashboard</h2>;
    }

    if (role === "manager") {
        return <h2>Manager Dashboard</h2>;
    }

    return <h2>User Dashboard</h2>;
}

This is often easier to understand than creating a complicated JSX expression.


2. Conditional Rendering Using if...else

You can use the normal JavaScript if...else statement.

function LoginStatus() {
    const isLoggedIn = true;

    if (isLoggedIn) {
        return <button>Logout</button>;
    } else {
        return <button>Login</button>;
    }
}

The logic is:

isLoggedIn
    |
    +---- true ----> Logout button
    |
    +---- false ---> Login button

This is useful when there are exactly two mutually exclusive UI states.


3. Conditional Rendering Using if...else if...else

When there are multiple possible states, use else if.

function StatusMessage({ status }: { status: string }) {

    if (status === "loading") {
        return <p>Loading...</p>;
    }
    else if (status === "success") {
        return <p>Data loaded successfully.</p>;
    }
    else if (status === "error") {
        return <p>Something went wrong.</p>;
    }
    else {
        return <p>Unknown status.</p>;
    }
}

This is appropriate when a value can have several distinct states.

For example:

loading
success
error
unknown

This pattern is very common when working with API calls.


4. Conditional Rendering Using the Ternary Operator

The ternary operator is one of the most commonly used techniques for conditional rendering.

Syntax:

condition ? valueIfTrue : valueIfFalse

For example:

function Welcome() {
    const isLoggedIn = true;

    return (
        <div>
            {isLoggedIn ? <h2>Welcome</h2> : <h2>Please Login</h2>}
        </div>
    );
}

The condition:

isLoggedIn

is evaluated.

If true:

<h2>Welcome</h2>

is rendered.

If false:

<h2>Please Login</h2>

is rendered.

Ternary with different components

function App() {
    const isLoggedIn = true;

    return (
        <div>
            {isLoggedIn ? <Dashboard /> : <Login />}
        </div>
    );
}

This is extremely common in React applications.

isLoggedIn
     |
     +---- true ----> Dashboard
     |
     +---- false ---> Login

5. Ternary Operator with Multiple Conditions

You can also use nested ternary expressions.

function Status({ status }: { status: string }) {

    return (
        <div>
            {
                status === "loading"
                    ? <p>Loading...</p>
                    : status === "success"
                        ? <p>Success</p>
                        : <p>Error</p>
            }
        </div>
    );
}

This works, but nested ternaries can quickly become difficult to read.

For example:

condition1
    ? result1
    : condition2
        ? result2
        : condition3
            ? result3
            : result4

For two conditions, ternary is excellent.

For many conditions, if...else if, a lookup object, or a switch is generally easier to maintain.


6. Conditional Rendering Using Logical AND &&

Another very important technique is the JavaScript logical AND operator:

condition && JSX

For example:

function Notification() {
    const hasNotification = true;

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

If:

hasNotification === true

React renders:

You have a new notification.

If:

hasNotification === false

nothing is rendered.

This is useful when you only want to display something when a condition is true.

Real-world example

function UserActions({ isAdmin }: { isAdmin: boolean }) {
    return (
        <div>
            <button>Profile</button>

            {isAdmin && (
                <button>Delete User</button>
            )}
        </div>
    );
}

Normal users see:

Profile

Administrators see:

Profile
Delete User

This is one of the most common patterns in React.


7. Why Does && Work?

The behavior comes from JavaScript's logical AND operator.

For example:

true && "Hello"

returns:

Hello

But:

false && "Hello"

returns:

false

React does not render false, so nothing appears.

Therefore:

{isAdmin && <button>Delete User</button>}

effectively means:

If isAdmin is true
    render button

Otherwise
    render nothing

8. Important Problem with && and Numbers

There is an important React pitfall with the && operator.

Consider:

function Messages() {
    const messageCount = 0;

    return (
        <div>
            {messageCount && <p>You have messages.</p>}
        </div>
    );
}

You might expect nothing to be displayed.

But React can render:

0

because:

0 && <p>You have messages.</p>

returns:

0

And 0 is renderable by React.

A safer approach is:

{messageCount > 0 && (
    <p>You have messages.</p>
)}

Now the condition itself produces a boolean:

messageCount > 0

If count is 0:

false

If count is 5:

true

So:

{messageCount > 0 && <p>You have messages.</p>}

is preferable.


9. Conditional Rendering Using Logical OR ||

The logical OR operator can also be useful.

const name = "";

return (
    <h2>
        {name || "Guest"}
    </h2>
);

If name contains a value:

Syed

React displays:

Syed

If name is an empty string:

Guest

The general idea is:

value || fallback

This is commonly used for default display values.

Another example

function UserName({ name }: { name?: string }) {
    return (
        <h2>
            {name || "Guest User"}
        </h2>
    );
}

If the name is unavailable, the fallback is displayed.

Important limitation

|| considers several values as falsy:

false
0
""
null
undefined
NaN

Therefore, if 0 is a valid value, || may not be appropriate.

For example:

const count = 0;

const result = count || 10;

The result becomes:

10

even though 0 might be a legitimate value.


10. Conditional Rendering Using Nullish Coalescing ??

The nullish coalescing operator is:

??

It is useful when you only want to provide a fallback for:

null
undefined

Example:

const name = null;

return (
    <h2>
        {name ?? "Guest"}
    </h2>
);

The result is:

Guest

But:

const count = 0;

return <p>{count ?? 10}</p>;

displays:

0

This differs from ||.

0 || 10

produces:

10

while:

0 ?? 10

produces:

0

Therefore:

Operator Fallback when
`  
?? Value is null or undefined

11. Conditional Rendering Using switch

When there are many possible conditions, switch can make the code easier to understand.

function StatusMessage({ status }: { status: string }) {

    switch (status) {
        case "loading":
            return <p>Loading...</p>;

        case "success":
            return <p>Data loaded successfully.</p>;

        case "error":
            return <p>Something went wrong.</p>;

        case "empty":
            return <p>No data found.</p>;

        default:
            return <p>Unknown status.</p>;
    }
}

This is particularly useful when one variable determines which UI should be displayed.

For example:

status
  |
  +-- loading --> Loading
  +-- success --> Success
  +-- error   --> Error
  +-- empty   --> No Data

12. Conditional Rendering Using a Variable

You don't always have to put the condition directly inside JSX.

You can calculate the UI first and then render the result.

function Welcome() {
    const isLoggedIn = true;

    let content;

    if (isLoggedIn) {
        content = <h2>Welcome back!</h2>;
    } else {
        content = <h2>Please login.</h2>;
    }

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

The important concept is:

let content;

The variable stores a React element.

Then:

{content}

renders that element.

This technique becomes useful when the rendering logic is more complex.


13. Conditional Rendering Using a Function

You can move complicated rendering logic into a function.

function Dashboard({ role }: { role: string }) {

    const renderContent = () => {

        if (role === "admin") {
            return <h2>Admin Dashboard</h2>;
        }

        if (role === "manager") {
            return <h2>Manager Dashboard</h2>;
        }

        return <h2>User Dashboard</h2>;
    };

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

This can help keep the main JSX clean when the conditional logic becomes large.

However, don't create unnecessary rendering functions for very simple conditions.

For example, this is unnecessarily complicated:

const renderButton = () => {
    return isLoggedIn ? <button>Logout</button> : <button>Login</button>;
};

You could simply use:

{isLoggedIn ? <button>Logout</button> : <button>Login</button>}

Use a function when it actually improves organization and readability.


14. Conditional Rendering Using Early Return

Early return is one of the cleanest patterns for handling states that should prevent the normal component UI from being rendered.

function Profile({ user }: { user: any }) {

    if (!user) {
        return <p>Please login to view your profile.</p>;
    }

    return (
        <div>
            <h2>{user.name}</h2>
            <p>{user.email}</p>
        </div>
    );
}

The component has two states:

user exists
    |
    +---- No ----> Login message
    |
    +---- Yes ---> Profile

This is particularly useful for:

  • Authentication
  • Authorization
  • Loading states
  • Error states
  • Missing data
  • Invalid parameters

15. Conditional Rendering for Loading State

One of the most common real-world scenarios is API data loading.

function Products() {
    const isLoading = true;

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

    return (
        <div>
            <h2>Products</h2>
        </div>
    );
}

In a real application, isLoading would normally come from state:

const [isLoading, setIsLoading] = useState(true);

The UI changes based on the state.

isLoading = true
        |
        v
Loading...

isLoading = false
        |
        v
Products

16. Conditional Rendering for Loading, Error and Success

A more realistic API scenario has multiple states.

function Products() {
    const status = "success";

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

    if (status === "error") {
        return <p>Unable to load products.</p>;
    }

    if (status === "success") {
        return <p>Products loaded successfully.</p>;
    }

    return null;
}

A typical application may have:

API Request
     |
     v
  Loading
     |
     +------ Error ------> Error UI
     |
     +------ Success ----> Data UI

This is one of the most important practical uses of conditional rendering.


17. Conditional Rendering with React State

Conditional rendering becomes especially powerful when combined with useState.

import { useState } from "react";

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

    return (
        <div>
            {isLoggedIn ? (
                <div>
                    <h2>Welcome User</h2>

                    <button onClick={() => setIsLoggedIn(false)}>
                        Logout
                    </button>
                </div>
            ) : (
                <div>
                    <h2>Please Login</h2>

                    <button onClick={() => setIsLoggedIn(true)}>
                        Login
                    </button>
                </div>
            )}
        </div>
    );
}

Initially:

isLoggedIn = false

The login UI appears.

After clicking Login:

isLoggedIn = true

React re-renders the component and displays the logged-in UI.

This demonstrates an important React concept:

State changes can cause conditional UI to change.


18. Conditional Rendering with Props

Conditional rendering can also depend on props.

type ButtonProps = {
    isAdmin: boolean;
};

function UserActions({ isAdmin }: ButtonProps) {

    return (
        <div>
            <button>Profile</button>

            {isAdmin && (
                <button>Manage Users</button>
            )}
        </div>
    );
}

Parent component:

<UserActions isAdmin={true} />

renders:

Profile
Manage Users

Whereas:

<UserActions isAdmin={false} />

renders:

Profile

This is commonly used for role-based UI.


19. Conditional Rendering Based on User Role

A real application may have different permissions.

function Dashboard({ role }: { role: string }) {

    return (
        <div>

            {role === "admin" && (
                <button>Manage Users</button>
            )}

            {role === "manager" && (
                <button>Approve Requests</button>
            )}

            {role === "user" && (
                <button>Create Request</button>
            )}

        </div>
    );
}

The UI is determined by the user's role.

Admin
  -> Manage Users

Manager
  -> Approve Requests

User
  -> Create Request

Important: Conditional rendering is only a UI mechanism. It should not be treated as a security mechanism.

For example:

{isAdmin && <button>Delete User</button>}

hiding the button does not prevent a malicious user from directly calling an API.

Authorization must also be enforced on the server/API.


20. Conditional Rendering with React Fragments

Conditional rendering can return multiple elements.

function UserInfo({ isLoggedIn }: { isLoggedIn: boolean }) {

    return (
        <>
            {isLoggedIn ? (
                <>
                    <h2>Welcome</h2>
                    <p>You are logged in.</p>
                </>
            ) : (
                <>
                    <h2>Guest User</h2>
                    <p>Please login.</p>
                </>
            )}
        </>
    );
}

The Fragment:

<>
    ...
</>

allows multiple elements without adding an unnecessary HTML element such as:

<div>

21. Conditional Rendering of a List

Conditional rendering can also be used when rendering collections.

function Users({ users }: { users: string[] }) {

    return (
        <div>
            {users.length > 0 ? (
                <ul>
                    {users.map(user => (
                        <li key={user}>{user}</li>
                    ))}
                </ul>
            ) : (
                <p>No users found.</p>
            )}
        </div>
    );
}

If users exist:

Users
  ├── Syed
  ├── Ahmed
  └── John

If there are no users:

No users found.

This is a common empty-state pattern.


22. Conditional Rendering Using Array Length

A shorter version is:

{users.length > 0 && (
    <UserList users={users} />
)}

But this only handles the positive case.

If you want to show something when the array is empty as well:

{
    users.length > 0
        ? <UserList users={users} />
        : <p>No users found.</p>
}

The ternary operator is therefore better when both states need different UI.


23. Conditional Rendering Using Optional Chaining

Optional chaining:

?.

is useful when an object may not exist.

For example:

<p>{user?.name}</p>

If user exists:

Syed

If user is null or undefined, React renders nothing for the expression.

Without optional chaining:

<p>{user.name}</p>

you could encounter an error when user is null or undefined.

Optional chaining is not technically a conditional rendering construct by itself, but it is frequently used with conditional UI.


24. Conditional Rendering with Optional Chaining and &&

You can combine them:

{user?.isAdmin && (
    <button>Manage Users</button>
)}

This means:

Does user exist?
       |
       +-- No --> Nothing
       |
       +-- Yes
             |
             +-- isAdmin?
                    |
                    +-- Yes --> Show button
                    |
                    +-- No --> Nothing

This is a very common React pattern.


25. Conditional Rendering Using null

A React component can return null.

Returning null means:

Render nothing.

Example:

function AdminButton({ isAdmin }: { isAdmin: boolean }) {

    if (!isAdmin) {
        return null;
    }

    return <button>Admin Panel</button>;
}

If:

isAdmin === true

the button is rendered.

If:

isAdmin === false

the component renders nothing.

This is useful when an entire component should disappear based on a condition.


26. Conditional Rendering of a Component

You can conditionally render an entire child component.

function App() {
    const isLoggedIn = true;

    return (
        <div>
            {isLoggedIn && <Dashboard />}
        </div>
    );
}

Or:

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

This is usually preferable to putting all the conditional logic inside the child component.

It allows the parent to determine which component should exist in the UI.


27. Conditional Rendering Using a Lookup Object

For a large number of fixed states, a lookup object can be very clean.

const statusComponents = {
    loading: <p>Loading...</p>,
    success: <p>Successfully loaded.</p>,
    error: <p>Something went wrong.</p>,
    empty: <p>No data available.</p>
};

Then:

function Status({ status }: { status: keyof typeof statusComponents }) {

    return (
        <div>
            {statusComponents[status]}
        </div>
    );
}

If:

status = "loading"

the loading UI is selected.

If:

status = "error"

the error UI is selected.

This approach can be cleaner than a long chain of conditions when the mapping is simple and fixed.


28. Conditional Rendering Using an Object with Components

You can also map states to components.

function Loading() {
    return <p>Loading...</p>;
}

function Success() {
    return <p>Success!</p>;
}

function ErrorMessage() {
    return <p>Error occurred.</p>;
}

const components = {
    loading: Loading,
    success: Success,
    error: ErrorMessage
};

Then:

function Status({ status }: { status: keyof typeof components }) {

    const Component = components[status];

    return <Component />;
}

This becomes useful when each state has more complicated UI.


29. Conditional Rendering Using switch with Components

Another clean pattern is:

function Status({ status }: { status: string }) {

    switch (status) {
        case "loading":
            return <Loading />;

        case "success":
            return <Success />;

        case "error":
            return <ErrorMessage />;

        default:
            return null;
    }
}

This is often more maintainable than deeply nested ternaries.


30. Conditional Rendering Using Boolean Expressions

You can use any JavaScript expression that evaluates to a boolean.

For example:

const age = 25;

return (
    <div>
        {age >= 18 && <p>Adult User</p>}
    </div>
);

Another example:

const balance = 1000;

return (
    <div>
        {balance > 0 && <p>Account has balance.</p>}
    </div>
);

Another:

const isVerified = true;

return (
    <div>
        {isVerified && <p>Account verified.</p>}
    </div>
);

The important point is that React can use JavaScript expressions inside JSX using:

{expression}

31. Conditional Rendering Using Multiple Boolean Conditions

You can combine conditions using JavaScript operators.

AND condition

{isLoggedIn && isAdmin && (
    <button>Delete User</button>
)}

The button appears only when:

isLoggedIn = true
AND
isAdmin = true

OR condition

{isAdmin || isManager ? (
    <button>Manage Requests</button>
) : (
    <p>Access denied.</p>
)}

The user gets access when either:

isAdmin
OR
isManager

is true.


32. Conditional Rendering with Complex Business Conditions

For complicated conditions, calculate the condition before the JSX.

Instead of:

{
    user &&
    user.isActive &&
    user.role === "admin" &&
    user.subscription?.isValid &&
    <AdminPanel />
}

you can make the logic easier to understand:

const canAccessAdminPanel =
    user &&
    user.isActive &&
    user.role === "admin" &&
    user.subscription?.isValid;

Then:

{canAccessAdminPanel && <AdminPanel />}

This separates business logic from presentation logic.


33. Conditional Rendering with useState for Show/Hide

A common example is showing and hiding content.

import { useState } from "react";

function Profile() {
    const [showDetails, setShowDetails] = useState(false);

    return (
        <div>
            <button onClick={() => setShowDetails(!showDetails)}>
                {showDetails ? "Hide Details" : "Show Details"}
            </button>

            {showDetails && (
                <div>
                    <p>Email: syed@example.com</p>
                    <p>Role: Developer</p>
                </div>
            )}
        </div>
    );
}

Initially:

Show Details

After clicking:

Hide Details

Email: syed@example.com
Role: Developer

This is one of the most practical combinations of:

State + Event + Conditional Rendering

34. Conditional Rendering for Form Validation

Conditional rendering is frequently used for validation messages.

function LoginForm() {
    const email = "";

    return (
        <div>
            <input type="email" />

            {!email && (
                <p>Email is required.</p>
            )}

            <button>Login</button>
        </div>
    );
}

When the condition indicates invalid input, the validation message appears.

In a real application, this would normally be connected to state.


35. Conditional Rendering for Error Messages

function UserProfile({ error }: { error: string | null }) {

    return (
        <div>
            {error && (
                <p>
                    Error: {error}
                </p>
            )}
        </div>
    );
}

When:

error = null

nothing is displayed.

When:

error = "Unable to load profile"

React displays:

Error: Unable to load profile

36. Conditional Rendering for Empty States

A professional application should usually handle empty data explicitly.

For example:

function ProductList({ products }: { products: string[] }) {

    if (products.length === 0) {
        return <p>No products found.</p>;
    }

    return (
        <ul>
            {products.map(product => (
                <li key={product}>{product}</li>
            ))}
        </ul>
    );
}

This provides a better user experience than displaying an empty screen.


37. Conditional Rendering with Three States

A typical component can have:

Loading
Error
Data

For example:

function ProductPage({
    isLoading,
    error,
    products
}: {
    isLoading: boolean;
    error: string | null;
    products: string[];
}) {

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

    if (error) {
        return <p>Error: {error}</p>;
    }

    if (products.length === 0) {
        return <p>No products found.</p>;
    }

    return (
        <ul>
            {products.map(product => (
                <li key={product}>{product}</li>
            ))}
        </ul>
    );
}

This is a very practical production pattern:

             API Request
                  |
                  v
              Loading?
             /        \
           Yes         No
           |            |
        Loading       Error?
                       /   \
                     Yes    No
                     |       |
                   Error   Empty?
                           /    \
                         Yes     No
                         |        |
                       Empty     Data

38. Conditional Rendering vs CSS Hiding

Conditional rendering and CSS hiding are not the same thing.

Conditional rendering

{isVisible && <div>Secret Content</div>}

When isVisible is false, the element is not rendered.

CSS hiding

<div style={{ display: isVisible ? "block" : "none" }}>
    Secret Content
</div>

The element still exists in the DOM, but CSS hides it.

Conceptually:

Conditional Rendering
        |
        +---- Element doesn't get rendered

CSS display:none
        |
        +---- Element exists but isn't displayed

This distinction can matter for performance, DOM behavior, accessibility, and component lifecycle.


39. Conditional Rendering Does Not Mean Changing the DOM Manually

React applications generally should not use:

document.getElementById(...)

to manually show or hide React UI.

Instead:

{isVisible && <Component />}

React determines what should exist in the UI.

This follows React's declarative programming model:

You describe what the UI should look like for a particular state, and React handles updating the DOM.


40. Conditional Rendering and Re-Rendering

Suppose:

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

Initially:

isLoggedIn = false

React renders:

<Login />

When:

setIsLoggedIn(true);

is executed, React re-renders the component.

Now:

isLoggedIn = true

and:

<Dashboard />

is rendered.

The important relationship is:

State
  |
  v
Condition
  |
  v
Different JSX
  |
  v
Different UI

41. All Major Conditional Rendering Techniques

The main techniques can be summarized as follows:

Technique Typical Use
if Completely different rendering branches
if...else Two different UI states
else if Multiple conditions
Ternary ? : Inline two-way rendering
&& Render something only when true
`  
?? Fallback for null / undefined
switch Multiple fixed states
Variable Store calculated JSX
Function Encapsulate complex rendering
Early return Exit early for loading/error/auth states
null Render nothing
Lookup object Map state/value to UI
State + condition Dynamic show/hide UI
Props + condition Role/permission-based UI
Optional chaining ?. Safely access potentially missing data

42. Which Technique Should You Use?

A useful rule is:

Use if / early return when the entire component changes

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

return <Dashboard />;

Use ternary when there are two UI choices

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

Use && when there is only a positive case

{isAdmin && <AdminPanel />}

Use ?? for null/undefined fallback

{name ?? "Guest"}

Use || when any falsy value should trigger the fallback

{name || "Guest"}

Use switch for multiple fixed states

switch (status) {
    case "loading":
        return <Loading />;
    case "success":
        return <Success />;
    case "error":
        return <Error />;
}

Use a lookup object for simple value-to-component mappings

const views = {
    loading: <Loading />,
    success: <Success />,
    error: <Error />
};

43. A Practical React Example Combining Multiple Techniques

Consider a product page:

function ProductPage() {
    const isLoading = false;
    const error = null;
    const products = ["Laptop", "Mouse", "Keyboard"];

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

    if (error) {
        return <p>Error loading products.</p>;
    }

    return (
        <div>
            <h2>Products</h2>

            {products.length > 0 ? (
                <ul>
                    {products.map(product => (
                        <li key={product}>
                            {product}
                        </li>
                    ))}
                </ul>
            ) : (
                <p>No products found.</p>
            )}

            {products.length > 0 && (
                <p>Total Products: {products.length}</p>
            )}
        </div>
    );
}

This single example demonstrates several techniques:

if
    |
    +-- Loading state

if
    |
    +-- Error state

ternary
    |
    +-- Data vs Empty state

&&
    |
    +-- Display product count

This is very close to how conditional rendering appears in real-world React applications.


44. Important React Concept: Conditional Rendering Is JavaScript

React does not provide a completely separate conditional-rendering language.

Instead, React uses JavaScript expressions and statements to determine what JSX should be returned.

For example:

const isLoggedIn = true;

Then:

{isLoggedIn && <Dashboard />}

uses JavaScript.

Similarly:

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

uses the JavaScript ternary operator.

And:

if (isLoggedIn) {
    return <Dashboard />;
}

uses a normal JavaScript if statement.

Therefore, a good understanding of JavaScript operators, boolean logic, arrays, objects, and functions is extremely important for React conditional rendering.


45. The Most Important Patterns to Remember

If you are preparing for React development or interviews, these are the patterns you should be comfortable with:

// 1. if
if (isLoggedIn) {
    return <Dashboard />;
}

return <Login />;
// 2. Ternary
{isLoggedIn ? <Dashboard /> : <Login />}
// 3. AND
{isAdmin && <AdminPanel />}
// 4. OR fallback
{name || "Guest"}
// 5. Nullish fallback
{name ?? "Guest"}
// 6. switch
switch (status) {
    case "loading":
        return <Loading />;

    case "success":
        return <Success />;

    case "error":
        return <Error />;

    default:
        return null;
}
// 7. Early return
if (!user) {
    return <Login />;
}
// 8. Render nothing
if (!isAdmin) {
    return null;
}

Final Mental Model

Think about React conditional rendering like this:

                 COMPONENT STATE
                       |
                       v
                 Evaluate Condition
                       |
          +------------+------------+
          |                         |
        TRUE                      FALSE
          |                         |
          v                         v
      JSX Branch A             JSX Branch B
          |                         |
          +------------+------------+
                       |
                       v
                    React
                       |
                       v
                      UI

The most important principle is:

Conditional rendering means deciding which React elements should be rendered based on the current state, props, data, or other JavaScript conditions.

In practice, you will use if / early returns for large branches, ternary for two alternatives, && for optional UI, ??/`||` for fallback values, and switch or lookup mappings for multiple states.

← Back to Articles