FOLASAYO SAMUEL OLAYEMI
SV_D_CURIOUS_SOFTWARE_ENGINEER'S BLOG

SV_D_CURIOUS_SOFTWARE_ENGINEER'S BLOG

How to use conditional rendering in ReactJS?

FOLASAYO SAMUEL OLAYEMI's photo
FOLASAYO SAMUEL OLAYEMI
·Mar 16, 2022·

1 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • We can render using the if Statement
  • Another way to conditionally render a React component is by using the Logic && operator.
  • Lastly, another way to conditionally render elements is by using a ternary operator.

There are several ways you can render conditionally with React.

We can render using the if Statement

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

Code Sample:

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

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

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

import React from 'react';
import ReactDOM from 'react-dom';

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'];
ReactDOM.render(
  <Garage cars={cars} />,
  document.getElementById('root')
);

If cars.length equates to true, the expression after && will render.

Lastly, another way to conditionally render elements is by using a ternary operator.

If the condition ? true : false.

Code Sample:

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

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

If the first condition is met <MadeGoal/> will be rendered else <MissedGoal/> will be rendered as alternative.

 
Share this