How to use If Condition inside map() in React JS?

Sep 30, 2022 . Admin

Hello Guys,

Are you looking for an example of react js map with condition. We will look at an example of how to use if condition in map in react js. I would like to share with you how to write if condition inside map in react js. I would like to show you if condition inside map react js. So, let us dive into the details.

In this example, we will create one "users" array and then i will simply display all data using map() function, Then we will use if condition inside map() function with react.js.

So, let's see follow the below step to create simple example.

Step 1: Create React JS App

In this step, open your terminal and execute the following command on your terminal to create a new react app:

npx create-react-app react-app-example
Step 2: Update App.js Component

Here, let's copy the below code and add on App.js file.

src/App.js
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';


function App() {

  /*------------------------------------------
  --------------------------------------------
  Users Lists
  --------------------------------------------
  --------------------------------------------*/
  const users = [
    {id: 1, name: 'Hardik', country: 'India'},
    {id: 2, name: 'Vimal', country: 'India'},
    {id: 3, name: 'Harshad', country: 'Canada'},
    {id: 4, name: 'Keval', country: 'Denmark'},
    {id: 5, name: 'Savan', country: 'USA'},
  ];

  return (
    <div className="App container">
      <h1>How to use if condition inside map() in React JS? - MyWebtuts.com</h1>

      <table className="table table-bordered">
        <thead>
          <tr>
            <th scope="col">ID</th>
            <th scope="col">Name</th>
            <th scope="col">Country</th>
          </tr>
        </thead>
        <tbody>
          {
              users.map((user) =>{

                if (user.id % 2 === 0) {
                    return <tr>
                    <th scope="row"><strong className="text-success">{user.id}</strong></th>
                    <td><strong className="text-success">{user.name}</strong></td>
                    <td><strong className="text-success">{user.country}</strong></td>
                  </tr>;
                } 

                return <tr>
                    <th scope="row">{user.id}</th>
                    <td>{user.name}</td>
                    <td>{user.country}</td>
                  </tr>
              })
          }
        </tbody>
      </table>

    </div>
  );
}

export default App;
Step 3: Run React JS App

In the last step run your project using bellow command.

npm start
Output

I hope it can help you...

#React JS