(https://i.stack.imgur.com/8sdxs.png)
Trying to get the nested data products.name to render on page. i tried doing this but it doesnt render anything, i want to get the products name and id ... but it is in nested array.I'm sure this is some syntax problem, thanks in advance
{data && data.categories.products?.map((product) => {
return <div>
<h1>Name : {product.products.name}</h1>
<h3>ID :{product.products.id} </h3>
</div>
})}
CodePudding user response:
If you want to render products for each category seperately
{data?.categories?.map((cat, catIdx) => {
return (
<div key={catIdx}>
<span>Category Name<span>
{
cat.products?.map((product) => {
return (
<div key={product.id}>
<h1>Name : {product.name}</h1>
<h3>ID :{product.id} </h3>
</div>
)
})
}
</div>
)
})}
If you want to all products
// use useMemo if performance is an issue
const allProducts = data?.categories?.reduce((acc, curr) => {
return [ ...acc, ...(curr.products ?? []) ]
}, [])
{
allProducts?.map((product) => {
return (
<div key={product.id}>
<h1>Name : {product.name}</h1>
<h3>ID :{product.id} </h3>
</div>
)
})
}
Hope it helps
CodePudding user response:
You have an extra .products
in your variables (inside the html).
{data && data.categories.products?.map((product) => {
return <div>
<h1>Name : {product.name}</h1>
<h3>ID :{product.id} </h3>
</div>
})}
CodePudding user response:
If you mean that each product
has a property with products
array, You need to loop again through the products
array, so you will have two nested map
.
{data && data.catergories.products?.map((product) => {
return <div>
{ product.products && product.products.map(subProducts => (<h1>Name : {subProducts.name}</h1>
<h3>ID :{subProducts .id} </h3> ))
</div>
})}