I want to render the list "products".Means there are 3 items in product array, I want to use map method to render this list. But getting TypeError: products.map is not a function
const products = [
{
id: 101,
name: "Skirt",
image: "https://i.pravatar.cc/48?u=118836",
price: 700,
},
{
id: 102,
name: "Jeans",
image: "https://i.pravatar.cc/48?u=933372",
price: 1500,
},
{
id: 103,
name: "Top",
image: "https://i.pravatar.cc/48?u=499476",
price: 1000,
},
];
function App() {
return (
<div className="App">
<RetriveProducts products={products} />
</div>
);
}
function RetriveProducts(products) {
return (
<div>
{products.map((product) => {
<ProductList
image={product.image}
name={product.name}
price={product.price}
/>;
})}
</div>
);
}
function ProductList(image, name, price) {
return (
<div>
<img src={image} alt={name} />
<h2>{name}</h2>
<span>{price}</span>
</div>
);
}
export default App;
I have also used forEach method but still getting the same issue.
Earlier I have used same array with map function, it worked but not working in this code. If you have any solution please post it.
>Solution :
The issue is you’re passing the products prop to the RetriveProducts component, so:
-
You will need to destructure the
propsobject to access theproductsarray. -
You would need to return the
ProductListcomponent.{products.map((product) => { // First way return <ProductList key={product.id} image={product.image} name={product.name} price={product.price} />; })} -
You will need to use
keyprop1.
CODE SAMPLE:
// ...rest of your code
function RetriveProducts({ products }) { // Destructure the props object to access the products array
return (
<div>
{products.map((product) => ( // <--- Second way
<ProductList
key={product.id} /* <--- add a key prop to each child component */
image={product.image}
name={product.name}
price={product.price}
/>
))}
</div>
);
}
1Keeping List items in order with key