Curriculum
Course: React
Login

Curriculum

React

Text lesson

React Conditional

In React, you can render components conditionally using various methods.

if Statement

We can use the if JavaScript statement to determine which component to render.

Example:

We’ll use the following two components:

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

Example:

Next, we’ll create a component that selects which component to render based on a condition.

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

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

Attempt to set the isGoal attribute to true.

Example:

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

Logical && Operator

Another method for conditionally rendering a React component is by using the && operator.

Example:

JavaScript expressions can be embedded in JSX using curly braces.

function Garage(props) {
 const cars = props.cars;
 return (
    <>
      <h1>Garage</h1>
      {cars.length > 0 &&
        <h2>
          You have {cars.length} cars in your garage.
        </h2>
      }
    </>
 );
}

const cars = ['Ford', 'BMW', 'Audi'];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage cars={cars} />);

If cars.length > 0 evaluates to true, the expression following && will be rendered. Try clearing the cars array.

Example:

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

Ternary Operator

You can also use a ternary operator to conditionally render elements.

condition ? true : false

We’ll return to the goal example.

Example:

Return the MadeGoal component if isGoal is true; otherwise, return the MissedGoal component.

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

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