Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 8 of 10 · React Basics and JSX
Interview question

What are different ways to do conditional rendering in React? React में conditional rendering के कितने तरीके हैं?

Answer
// 1. if-else statement
function WelcomeMessage({ isLoggedIn }) {
    if (isLoggedIn) {
        return <h1>Welcome back!</h1>;
    }
    return <h1>Please log in</h1>;
}

// 2. Ternary operator
function WelcomeMessage({ isLoggedIn }) {
    return isLoggedIn ? <h1>Welcome!</h1> : <h1>Login</h1>;
}

// 3. Logical && operator
function Notification({ unreadCount }) {
    return (
        <div>
            <p>Messages</p>
            {unreadCount > 0 && <span className='badge'>{unreadCount}</span>}
        </div>
    );
}

// 4. Switch statement
function Status({ status }) {
    switch(status) {
        case 'loading':
            return <p>Loading...</p>;
        case 'success':
            return <p>Success!</p>;
        case 'error':
            return <p>Error occurred</p>;
        default:
            return <p>Unknown status</p>;
    }
}

// 5. Object mapping
function Status({ status }) {
    const statusMessages = {
        loading: <p>Loading...</p>,
        success: <p>Success!</p>,
        error: <p>Error occurred</p>
    };
    
    return statusMessages[status] || <p>Unknown</p>;
}

// 6. IIFE (Immediately Invoked Function Expression)
function Status({ status }) {
    return (
        {(() => {
            if (status === 'loading') return <p>Loading</p>;
            if (status === 'success') return <p>Success</p>;
            return <p>Error</p>;
        })()}
    );
}

// 7. Separate component for condition
function WelcomeMessage({ isLoggedIn }) {
    return isLoggedIn ? <LoggedInView /> : <LoggedOutView />;
}

function LoggedInView() {
    return <h1>Welcome back!</h1>;
}

function LoggedOutView() {
    return <h1>Please log in</h1>;
}

// 8. Variable assignment
function Status({ status }) {
    let message;
    
    if (status === 'loading') {
        message = <p>Loading...</p>;
    } else if (status === 'success') {
        message = <p>Success!</p>;
    } else {
        message = <p>Error</p>;
    }
    
    return <div>{message}</div>;
}
Conditional rendering के तरीके:

1. if-else
if (isLoggedIn) return <h1>Welcome</h1>;
return <h1>Login</h1>;

2. Ternary operator
isLoggedIn ? <h1>Welcome</h1> : <h1>Login</h1>

3. Logical &&
{isLoggedIn && <h1>Welcome</h1>}

4. Switch statement
switch(status) {
    case 'loading': return <p>Loading</p>;
}

5. Object mapping
const views = {
    loading: <p>Loading</p>,
    success: <p>Success</p>
};
return views[status];

Was this answer clear?