0

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>  
  )
}

1 Answer 1

2

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}
    />
  )
})
Sign up to request clarification or add additional context in comments.

2 Comments

Nice one, this works. I tried with something simple to check with hasOwnProperty, if (product.hasOwnProperty('promoimage')) { return true } and noticed that the last item disappeared. No idea why. I've added the code above. But I understand your solution. Thank you!!
Glad to hear. You can also accept the reply as solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.