🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to React Notes
Topic #27

React Conditionals


In React, you can conditionally render components.

There are several ways to do this.


if Statement

We can use the if JavaScript operator to decide which component to render.

Example:

function MissedGoal() {
  return <h1>MISSED!</h1>;
}

function MadeGoal() {
  return <h1>Goal!</h1>;
}

Example:

function Goal(props) {
  const isGoal = props.isGoal;
  if (isGoal) {
    return <MadeGoal/>;
  }
  return <MissedGoal/>;
}

createRoot(document.getElementById('root')).render(
  <Goal isGoal={false} />
);

Try changing the isGoal attribute to true:

Example:

createRoot(document.getElementById('root')).render(
  <Goal isGoal={true} />
);

Logical && Operator

Another way to conditionally render a React component is by using the && operator.

In the example below, the heading will only be rendered if the props.brand property is not empty:

Example:

function Car(props) {
  return (
    <>
      {props.brand && <h1>My car is a {props.brand}!</h1>}
    </>
  );
}

createRoot(document.getElementById('root')).render(
  <Car brand="Ford" />
);

If props.brand evaluates to true, the expression after && will render.

Try emptying the brand property:

Example:

createRoot(document.getElementById('root')).render(
  <Car />
);

Ternary Operator

Another way to conditionally render elements is by using a ternary operator.

condition ? true : false

We will go back to the goal example.

Example:

function Goal(props) {
  const isGoal = props.isGoal;
  return (
    <>
      { isGoal ? <MadeGoal/> : <MissedGoal/> }
    </>
  );
}

createRoot(document.getElementById('root')).render(
  <Goal isGoal={false} />
);

To learn more, see the ternary operator section.

Want to go beyond the notes?

Join CodingNow 2.0's React course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

React Conditionals – FAQs

Quick answers about learning React Conditionals in React.

This free note from CodingNow 2.0 explains React Conditionals in React — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every React topic on CodingNow 2.0, including React Conditionals, is 100% free with no signup required.
With focused practice, most students grasp React Conditionals in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now