REACT Conditionals

In React, conditionals allow you to control what content is rendered based on specific conditions. You can use JavaScript’s conditional logic within JSX to render components, elements, or HTML dynamically.

1. Conditional Rendering with if Statements

Use a standard if statement to determine what to render outside the JSX block.

Example:

function App() {
    const isLoggedIn = true;

    if (isLoggedIn) {
        return <h1>Welcome, User!</h1>;
    } else {
        return <h1>Please Log In</h1>;
    }
}

export default App;

Try It Now

2. Inline Conditional Rendering with Ternary Operators

Ternary operators are a concise way to render conditionally within JSX.

Example:

function App() {
    const isLoggedIn = true;

    return (
        <div>
            {isLoggedIn ? <h1>Welcome, User!</h1> : <h1>Please Log In</h1>}
        </div>
    );
}

export default App;

Try It Now

3. Rendering with Logical AND (&&)

Use logical AND to render content only if a condition is true.

Example:

function App() {
    const hasNotifications = true;

    return (
        <div>
            <h1>Welcome, User!</h1>
            {hasNotifications && <p>You have new notifications.</p>}
        </div>
    );
}

export default App;

Try It Now

4. Conditional Rendering with if-else Inside JSX

Although it’s less common, you can use an if-else statement within JSX by wrapping it in a function or expression.

Example:

function App() {
    const isLoggedIn = true;

    const renderMessage = () => {
        if (isLoggedIn) {
            return <h1>Welcome, User!</h1>;
        } else {
            return <h1>Please Log In</h1>;
        }
    };

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

export default App;

Try It Now

5. Conditional Rendering with Switch Statements

For multiple conditions, a switch statement can be cleaner than nested if-else.

Example:

function App() {
    const userRole = "admin";

    const renderMessage = () => {
        switch (userRole) {
            case "admin":
                return <h1>Welcome, Admin!</h1>;
            case "editor":
                return <h1>Welcome, Editor!</h1>;
            default:
                return <h1>Welcome, Guest!</h1>;
        }
    };

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

export default App;

Try It Now

6. Conditional Rendering with Short-Circuit Operators

Example: Default Fallback

function App() {
    const userName = null;

    return (
        <div>
            <h1>{userName || "Guest"}</h1>
        </div>
    );
}

export default App;

Try It Now

  • If userName is null or undefined, “Guest” is rendered.

 

7. Conditional Rendering in Lists

You can filter or map elements conditionally when rendering lists.

Example:

function App() {
    const users = [
        { id: 1, name: "John", isActive: true },
        { id: 2, name: "Jane", isActive: false },
    ];

    return (
        <ul>
            {users
                .filter((user) => user.isActive)
                .map((user) => (
                    <li key={user.id}>{user.name}</li>
                ))}
        </ul>
    );
}

export default App;

Try It Now

8. Conditional Rendering with Fragments

React fragments can be used to return multiple elements without adding extra DOM nodes.

Example:

function App() {
    const isPremium = true;

    return (
        <>
            <h1>Welcome!</h1>
            {isPremium ? <p>You have premium access.</p> : <p>Upgrade to premium!</p>}
        </>
    );
}

export default App;

Try It Now

9. Combining Multiple Conditions

Combine multiple conditions using logical operators or nested ternary statements.

Example:

function App() {
    const isLoggedIn = true;
    const hasNotifications = false;

    return (
        <div>
            {isLoggedIn ? (
                hasNotifications ? (
                    <p>You have notifications.</p>
                ) : (
                    <p>No new notifications.</p>
                )
            ) : (
                <p>Please log in to see notifications.</p>
            )}
        </div>
    );
}

export default App;

Try It Now

10. Handling Edge Cases

Avoid rendering components with missing or undefined data.

Example:

function App() {
    const user = null;

    return (
        <div>
            {user ? <h1>Welcome, {user.name}</h1> : <h1>Please log in.</h1>}
        </div>
    );
}

export default App;

Try It Now

Key Takeaways

  1. Use the right approach: Choose if, ternary, or logical operators based on complexity and readability.
  2. Optimize for performance: Use key props when rendering lists conditionally.
  3. Handle null or undefined values: Ensure fallback rendering for edge cases.

React conditionals give you the flexibility to create dynamic and interactive interfaces based on various application states.