React Tutorial menu

React Conditional Rendering

Conditional rendering means showing different content depending on a condition, such as whether a user is logged in.

Using if

Because components are JavaScript functions, you can use a normal if statement before the return.

Example

jsx
function Greeting({ isLoggedIn, name }) {
  if (isLoggedIn) {
    return <h2>Welcome back, {name}!</h2>;
  }
  return <h2>Please log in to see your courses.</h2>;
}

<Greeting isLoggedIn={true} name="Ayesha" />
<Greeting isLoggedIn={false} />
Output
Welcome back, Ayesha!
Please log in to see your courses.

The Ternary Operator

Inside JSX you cannot use if, but you can use the ternary operator condition ? a : b.

Example

jsx
function StockLabel({ quantity }) {
  return (
    <p>
      {quantity > 0 ? "In stock: " + quantity + " left" : "Sold out"}
    </p>
  );
}

<StockLabel quantity={4} />
<StockLabel quantity={0} />
Output
In stock: 4 left
Sold out

The ternary can also choose between two pieces of JSX:

Example

jsx
{isAdmin ? <AdminPanel /> : <StudentPanel />}

The && Operator

When you want to show something or nothing, use &&. If the left side is true, React shows the right side.

Example

jsx
function Inbox({ unread }) {
  return (
    <div>
      <h2>Messages</h2>
      {unread > 0 && <p>You have {unread} new messages.</p>}
    </div>
  );
}

With unread={3} the paragraph appears. With unread={0} it does not.

Be careful with numbers on the left of &&. {count && <p>...</p>} shows a 0 on the page when count is 0. Write a real true/false condition such as count > 0 && instead.

Returning null

A component can return null to render nothing at all.

Example

jsx
function Warning({ show, message }) {
  if (!show) {
    return null;
  }
  return <div className="warning">{message}</div>;
}

Using a Variable

For more complex logic, store JSX in a variable first, then use it in the return.

Example

jsx
function ResultCard({ marks }) {
  let grade;
  if (marks >= 80) {
    grade = <strong>A grade, excellent work!</strong>;
  } else if (marks >= 60) {
    grade = <span>B grade, good effort.</span>;
  } else {
    grade = <span>Keep practising, you can do it.</span>;
  }

  return (
    <div>
      <p>Marks: {marks}</p>
      {grade}
    </div>
  );
}

<ResultCard marks={85} />
Output
Marks: 85
A grade, excellent work!

Which One to Use?

SituationBest choice
Two different resultsTernary a ? b : c
Show something or nothingcondition && <X />
Many casesif / else if before the return
Hide the whole componentreturn null

Good conditional rendering keeps your JSX easy to read. If a ternary becomes long or nested, move the logic into an if statement or a separate component.

Exercise

Exercise

What does {isOpen && <Menu />} show when isOpen is false?

Learn React with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp