DEV Community

Md Yusuf
Md Yusuf

Posted on

Conditional Rendering in React

Conditional rendering in React allows you to render different components or elements based on certain conditions, such as state or props. Here are some common methods to achieve conditional rendering:

1. Using If-Else Statements

You can use standard JavaScript if-else statements inside your component.

function MyComponent({ isLoggedIn }) {
    if (isLoggedIn) {
        return <h1>Welcome back!</h1>;
    } else {
        return <h1>Please sign in.</h1>;
    }
}
Enter fullscreen mode Exit fullscreen mode

2. Using Ternary Operators

This is a concise way to render content based on a condition.

function MyComponent({ isLoggedIn }) {
    return (
        <h1>
            {isLoggedIn ? 'Welcome back!' : 'Please sign in.'}
        </h1>
    );
}
Enter fullscreen mode Exit fullscreen mode

3. Using Logical && Operator

You can use the logical AND operator to render a component only if a condition is true.

function MyComponent({ isLoggedIn }) {
    return (
        <div>
            {isLoggedIn && <h1>Welcome back!</h1>}
            {!isLoggedIn && <h1>Please sign in.</h1>}
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode

4. Switch Statement

For more complex conditions, you can use a switch statement.

function MyComponent({ status }) {
    switch (status) {
        case 'loading':
            return <h1>Loading...</h1>;
        case 'success':
            return <h1>Data loaded successfully!</h1>;
        case 'error':
            return <h1>There was an error!</h1>;
        default:
            return null;
    }
}
Enter fullscreen mode Exit fullscreen mode

Example

Here’s a full example using functional components:

import React from 'react';

function App() {
    const [isLoggedIn, setIsLoggedIn] = React.useState(false);

    return (
        <div>
            <button onClick={() => setIsLoggedIn(!isLoggedIn)}>
                {isLoggedIn ? 'Logout' : 'Login'}
            </button>
            {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>}
        </div>
    );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Summary

Choose the method that best suits your needs based on the complexity of your conditions and your personal coding style. Let me know if you need more examples or explanations!

Top comments (0)