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 JSXJavaScript XML syntax by iterating over an array and rendering each item in the array as a component.

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')
);
Displaying a list of items from an array in React

Code explanation

  • Line 1: We import React from 'react'.

  • Line 3: We create the App component using an arrow function.

  • Line 5: We define an array called names that 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 DOMDocument Object Model.

  • Line 9: We render an <h1> element with the text List of Names.

  • Line 10: The <ul> tag represents an unordered list, where we will render the names from the names array.

  • Line 11: We use the map function to iterate over each element in the names array. The map function 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 the names array. The key prop is set to the index value of each name, which helps React efficiently update and re-render the list. The name variable represents the current name being iterated.

  • Line 19: We export the App component as the default export so that it can be imported and used in other parts of the application.

Free Resources