Reputation: 25
Here's an example of the static json data.
I'm having trouble rendering the 'promoimage' from the array.
I'm not 100% sure how to go about this to solve it. I was playing arround and wanted to check if 'promoimage' exists, but nothing was returned? Any advice how to achieve this?
[
{
"title": "some title",
"promoimage": "image.jpg",
"url": "#"
},
{
"title": "some title",
"image": "example.jpg",
"url": "#"
},
{
"title": "some other title",
"promoimage": "image.jpg",
"url": "#"
},
{
"title": "title",
"image": "example.jpg",
"url": "#"
},
]
My React component:
import products from '../product-data.json';
...
export const CustomSlider = () => {
// Here I'm using react-slick
const productList = products.map((product, i) => {
const uniqueItems = [];
if (uniqueItems.indexOf(product.imageone) === -1) {
uniqueItems.push(product.imageone);
}
/* This works
if (product.hasOwnProperty('promoimage')) {
return true
}
*/
return <Product key={i} {...product} />;
}
);
return (
<Slider>
{productList}
</Slider>
)
}
Upvotes: 0
Views: 250
Reputation: 10917
The code is sending all object keys to Product
, as props. Particularly this part {...product}
is expanded into this:
<Product
key={i}
title="some title"
promoimage="image.jpg"
url="#"
/>
This is called spreading.
Now, I suspect <Product>
doesn't know what to do with promoimage
, but knows what to do with image
. We haven't sent any image
so we have to fix that. We can do so by either modifying product so that it renders image || promoimage
, or change our parsing to this:
const productList = products.map((product, i) => {
const uniqueItems = []
if (uniqueItems.indexOf(product.promoimage) === -1) {
uniqueItems.push(product.promoimage)
}
return (
<Product
key={i}
{...product}
image={product.image || product.promoimage}
/>
)
})
Upvotes: 2