Rendering lists with React using map()

Jeff P
2 min readDec 16, 2023

--

creating a new array

Let’s imagine we have an array of Pizza objects. We’ll call our array “pizzaData”…

const pizzaData = [
{
name: "Focaccia",
ingredients: "Bread with italian olive oil and rosemary",
price: 6,
photoName: "pizzas/focaccia.jpg",
soldOut: false,
},
{
name: "Pizza Margherita",
ingredients: "Tomato and mozarella",
price: 10,
photoName: "pizzas/margherita.jpg",
soldOut: false,
},
{
name: "Pizza Spinaci",
ingredients: "Tomato, mozarella, spinach, and ricotta cheese",
price: 12,
photoName: "pizzas/spinaci.jpg",
soldOut: false,
},
{
name: "Pizza Funghi",
ingredients: "Tomato, mozarella, mushrooms, and onion",
price: 12,
photoName: "pizzas/funghi.jpg",
soldOut: false,
},
{
name: "Pizza Salamino",
ingredients: "Tomato, mozarella, and pepperoni",
price: 15,
photoName: "pizzas/salamino.jpg",
soldOut: true,
},
{
name: "Pizza Prosciutto",
ingredients: "Tomato, mozarella, ham, aragula, and burrata cheese",
price: 18,
photoName: "pizzas/prosciutto.jpg",
soldOut: false,
},
];

The way we would render this list of Pizza objects would be to use the map() function, which will create a new array.

So for example, we could write…

      <ul className="pizzas">
{pizzaData.map((pizza) => (
<Pizza pizzaObj={pizza} key={pizza.name} />
))}
</ul>

so we map over pizzaData with pizzaData.map()

For each element in the array (which happens to be pizza objects) we create a new component called Pizza and we create a “prop” called pizzaObj, and then pass it the element (i.e. the pizza object) as well as supplying a unique key, which react expects when using the map() function to render lists.

So now, when we come to render all of the Pizza objects, we would do the following:

function Pizza(props) {
return (
<li className="pizza">
<img src={props.pizzaObj.photoName} alt={props.pizzaObj.name} />
<div>
<h3>{props.pizzaObj.name}</h3>
<p>{props.pizzaObj.ingredients}</p>
<span>{props.pizzaObj.price}</span>
</div>
</li>
);
}

so our Pizza component will receive an image, an image alt name, a name for the h3 header, the ingredients, and the price.

It will do this for every element (pizza object) in the “pizzaData” array, so if there are six elements (pizza objects), then there will be six <li> list elements created.

--

--

Jeff P
Jeff P

Written by Jeff P

I tend to write about anything I find interesting. There’s not much more to it than that really :-)

No responses yet