How to display a list of items from an array in React
In React, we can display a list of items from an array by using the map function and
In this Answer, we'll learn how to display a list of items from an array in React.
Step 1: Create a new React project
To get started, open the terminal and navigate to the directory where the React project will be created. We have the option to set up the project using either Vite or Create React.
Regardless of the method selected, the new React project should have the basic project structure. Once the project is created, remove the preexisting code and styles in the index.css, App.js, and App.css files.
Step 2: Create the App component
Navigate to the src directory and locate the App.js file which will be modified to create our component. In the App.js file, we'll include the following code snippet, which demonstrates how to render a list of items from an array in React.
Code example
import React from 'react';
require('./style.css');
import ReactDOM from 'react-dom';
import App from './app.js';
ReactDOM.render(
<App />,
document.getElementById('root')
);
Code explanation
Line 1: We import
Reactfrom'react'.Line 3: We create the
Appcomponent using an arrow function.Line 5: We define an array called
namesthat contains the list of names we want to display.Line 7: We declare a return statement that returns the JSX code that will be rendered to the
.DOM Document Object Model Line 9: We render an
<h1>element with the textList of Names.Line 10: The
<ul>tag represents an unordered list, where we will render the names from thenamesarray.Line 11: We use the
mapfunction to iterate over each element in thenamesarray. Themapfunction takes a callback function that will be invoked for each element of the array.Line 12: Inside the callback function, we render an
<li>element for each name in thenamesarray. The key prop is set to theindexvalue of each name, which helps React efficiently update and re-render the list. Thenamevariable represents the current name being iterated.Line 19: We export the
Appcomponent as the default export so that it can be imported and used in other parts of the application.