Conditional rendering in React

Conditional rendering in React is a way to render different UI elements or components based on certain conditions, usually determined by state or props. Essentially, it lets your component “decide” what to display dynamically.

React uses JavaScript logic inside JSX, so you can use if statements, ternary operators, or logical && for conditional rendering.


1. Using if-else

import React, { useState } from "react";

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

  if (isLoggedIn) {
    return <h1>Welcome back!</h1>;
  } else {
    return <h1>Please sign in.</h1>;
  }
}

export default Greeting;

Here, React checks the isLoggedIn state and renders a different message accordingly.


2. Using Ternary Operator

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

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

The ternary operator is concise and works well inside JSX.


3. Using Logical AND (&&)

If you want to render something only when a condition is true:

function Notification({ unreadMessages }) {
  return (
    <div>
      <h1>Hello!</h1>
      {unreadMessages.length > 0 && (
        <h2>You have {unreadMessages.length} unread messages.</h2>
      )}
    </div>
  );
}

Here, the <h2> is rendered only if unreadMessages.length > 0.


✅ Summary:

  • if-else → Full control, can return different components.
  • Ternary (? :) → Inline conditional rendering.
  • && → Render something only when condition is true.

Leave a Reply