How to use map() to Create Lists in ReactJS ?
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:
Project Structure: It will look like the following.
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.
Step to Run Application: Run the application using the following command from the root directory of the project:
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.