Skip to content
Related Articles

Related Articles

Improve Article

How to use map() to Create Lists in ReactJS ?

  • Last Updated : 23 Jul, 2021

An array in JavaScript comes with a plethora of functions to work with. A map() is one such function that is used to create a list of objects by calling a function on each element of the array. In React, we can use the map() function to map a list of values to a list of components.

Let’s see how we can create a list in react using a simple project. The project has a list of fruit names, and we will change them into a list of components rendered in the browser.

Creating React Application And Installing Module:

  • Step 1: Create a React application using the following command:

    npx create-react-app listmapdemo

     



  • Step 2: After creating your project folder i.e. listmapdemo, move to it using the following command:

    cd listmapdemo

Project Structure: It will look like the following.

Project Structure

Example: While creating components using the map, react expects a key prop passed to each component being built. It will still render if the key is not passed, but you will see a warning from React about it in the console. In the App.js file, we have defined a list of fruits which is then mapped to a list of divs.

App.js




import React from "react"
  
function App() {
  
  // Declared an array of items
  const fruits = [
    'Apple',
    'Mango',
    'Banana',
    'GFG'
  ];
  
  // Some styling for the items
  const styles = {
    backgroundColor: 'white',
    width: '50px',
    marginBottom: '10px',
    padding: '10px',
    color: 'green',
    boxShadow: 'rgb(0,0,0,0.44) 0px 5px 5px',
  };
  
  return <>
    {
      /*  This maps each array item to a div adds
      the style declared above and return it */
      fruits.map(fruit => <div key={fruit} 
            style={styles}>{fruit}</div>)
    }
  </>;
}
  
export default App;

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Explanation: We declared a list of fruits that will be used to render divs. The styles object contains CSS styles for each item, it simply adds some margin, padding and some shadow. Finally, the App function returns a list of divs that are returned by calling map() on the fruits array. We added the styles object to the style attribute of each div.




My Personal Notes arrow_drop_up
Recommended Articles
Page :