0

I have a list of products which are mapped from an object and listed in a grid, displaying the image and title. Currently, when the user reaches the products view, the product images seem to take time to load in, instead of being visible straight away.

I'm aware there is a way to preload them, however I'm unsure how this would be done in this instance. How would I go about this?

//ProductData.js

const ProductData = [
  {
    id: 1,
    name: 'Product 1',
    slug: 'product-1',
    static_img: 'product_1_static.jpg',
  },
  {
    id: 2,
    name: 'Product 2',
    slug: 'product-2',
    static_img: 'product_2_static.jpg',
  },
  {
    id: 3,
    name: 'Product 3',
    slug: 'product-3',
    static_img: 'product_3_static.jpg',
  },
];

export default ProductData

// ProductResults.js

function ResultsList() {
      const { choices, setChoices } = useContext(ChoicesContext);
      const ProductsResult = ProductData.filter(x => x.categories.includes(choices.category) && x.waterTypes.includes(choices.waterType) && x.feedTypes.includes(choices.feedType));

      return (
        <div id="productResults">
          {ProductsResult.map((item, i) => (
            <div key={i} className="product">
              <Link
                onClick={() => setChoices({ ...choices, productSelected: item.name })}
                to={{
                  pathname: '/products/' + item.slug,
                  name: item.name,
                }}
              >
                <img src={require(`../images/sequences/${item.static_img}`)} alt="" />
                <h4>{item.name}</h4>
              </Link>
            </div>
          ))}
        </div>
      )
    } 
BEDev
  • 699
  • 1
  • 5
  • 9
  • What about the natural delay of loading the image from the remote server? If that's indeed the case, you can look into image preloading. – Boaz May 07 '20 at 15:11
  • Does this answer your question? [How to preload images in React.js?](https://stackoverflow.com/questions/42615556/how-to-preload-images-in-react-js) – Boaz May 07 '20 at 15:13
  • Adding to @Boaz-ReinstateMonica, you might also need to consider the size of the images you are loading. If they are large, high-res, do they need to be? you can create internet friendly version of the images, which will load faster - if that is the case – developer May 07 '20 at 15:15
  • @Boaz-ReinstateMonica it does, although how would I implement this with my object and map above? I'm fairly new to react so any direction would be much appreciated. – BEDev May 07 '20 at 15:40

0 Answers0