D DevBrainBox

React Conditional Rendering

Conditional Rendering

Conditional Rendering in React means displaying different UI elements based on conditions like values, states, or props.

1. Using if-else Statements

//instagram.jsx
function Instagram(props) {
    if (props.isLoggedIn) {
        return (
            <>
                <h2>Welcome on Instagram</h2>
            </>
        )
    } else {
        return (
            <>
                <h2>Please login here.</h2>
                <button>Login</button>
            </>
        )
    }
}
export default Instagram

//app.js
import Instagram from './Instagram';
function App() {
  return (
    <>
        <h1>Instagram</h1>
        <Instagram isLoggedIn={false} />
    </>
  );
}

export default App;

2. Using Ternary Operator

function Instagram(props) {
    return(
        <>
            {props.isLoggedIn ? <h2>Welcome to Instagram</h2> : <h2>Login here</h2>}
        </>
    )
}
export default Instagram

3. Using && Operator (short-circuiting)

function Cart(props) {
  return (
    <div>
      <h2>My Cart</h2>
      {props.items.length > 0 && <p>You have {props.items.length} items</p>}
    </div>
  );
}

// Usage
<Cart items={['Apple', 'Banana']} />

4. Conditional Rendering with switch

function StatusMessage({ status }) {
  switch (status) {
    case 'loading':
      return <p>Loading...</p>;
    case 'success':
      return <p>Data loaded!</p>;
    case 'error':
      return <p>Error loading data.</p>;
    default:
      return <p>Unknown status.</p>;
  }
}

// Usage
<StatusMessage status="success" />
MethodBest For
if/elseClear logic before returning JSX
Ternary ? :Inline rendering with two possible values
&&When only rendering something if true
switchMultiple conditions

On this page