How to use Map() Function in React JS?

Sep 29, 2022 . Admin

Hey Artisan,

In this quick example, let's see react js map() function example. This article goes in detailed on how to use map function in react js. This article goes in detailed on react.js foreach loop using map(). This example will help you map function example in react.js. Here, Create a basic example of how to implement map function in react js.

In this example, we will create one "users" array and then i will simply display using "map()" function in react js app.

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, we will call two apis for getting posts and another for deleting post using axios request.

src/App.js
import './App.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 Map() Function 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) =>
                  <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