React Conditional Rendering

React allows you to render components based on specific conditions, providing flexibility in your UI.


Using the if Statement

The if statement is a straightforward way to determine which component should be displayed.

First, define two components:

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

function Score() {
  return <h1>Scored!</h1>;
}

Next, create a component that decides which one to render based on a condition:

function Outcome(props) {
  const hasScored = props.hasScored;
  if (hasScored) {
    return <Score />;
  }
  return <Miss />;
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Outcome hasScored={false} />);

Try changing the hasScored attribute to true:

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Outcome hasScored={true} />);




Using the Logical && Operator

The && operator is another method for conditional rendering in React.

Embed JavaScript expressions in JSX using curly braces:

function Parking(props) {
  const vehicles = props.vehicles;
  return (
    <>
      <h1>Parking Lot</h1>
      {vehicles.length > 0 &&
        <h2>
          You have {vehicles.length} vehicles in your parking lot.
        </h2>
      }
    </>
  );
}

const vehicles = ['Toyota', 'Honda', 'Chevy'];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Parking vehicles={vehicles} />);

If vehicles.length > 0 evaluates to true, the expression after && will render.

Try emptying the vehicles array:

const vehicles = [];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Parking vehicles={vehicles} />);




Using the Ternary Operator

The ternary operator provides a concise way to conditionally render elements.

Syntax:

condition ? true : false

Returning to the goal example:

Return the Score component if hasScored is true, otherwise return the Miss component:

function Outcome(props) {
  const hasScored = props.hasScored;
  return (
    <>
      {hasScored ? <Score /> : <Miss />}
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Outcome hasScored={false} />);
Scroll to Top