Rendering list

To render (show) a list of items in a React app you will need:

  • The list of items. eg. an array of items.

  • A way to loop on the array .

  • With every iteration of the loop render the list item in hand.

  • Make sure that every rendered list item has a unique key (an id-like that is not repeated all over the component).

Let's see this in action

import React from "react";

function App() {
  const groceryList = ["Potato", "Bread", "Milk", "Carrot"];
    return (
      <div>
	 <h1>Grocery List</h1>
	 <ul>
	   {
	     groceryList.map((item) => (<li key={Date.now()}>{item}</li>))
	   }
	 </ul>
     </div>
    );
}
jsx
export default App;

And that's what was rendered:

As you can see:

  • We used array method map to loop on the groceryList array.

  • map method returns a new array of HTML elements

  • elements. Each element contains one of the array's items, and has a key attribute with its value equal to the index of each array's item.

  • Index is not the best unique key we can use but we use it here for simplicity.

Last updated