0

I am unable to display images in img tag in Reactjs

<ul className="products">
      {products.map((product) => (
        <li key={product._id}>
          <div className="product">
            <Link to={"/product/" + product._id}>
              <img className="product-image" src={product.image} alt="product" />
            </Link>
            <div className="product-name">
              <Link to={"/product/" + product._id}>{product.name}</Link>
            </div>
            <div className="product-brand">{product.brand}</div>
            <div className="product-price">${product.price}</div>
            <div className="product-rating">
              {product.rating} Stars ({product.numReviews} Reviews)
            </div>
          </div>
        </li>
      ))}
    </ul>

Every other data like product.name, product.price etc is getting displayed but problem lies with product.image .

object image

The above pic shows my products array.

Web page view

The above pic shows each component the page

1 Answers1

0

These issue appears since React is using webpack as bundler by default. When using assets with the bundler you should provide the image path with require('...') or directly import the asset as a module with import

In your case <img className="product-image" src={product.image} alt="product" /> should be changed to
<img className="product-image" src={require(product.image)} alt="product" /> or you should restructure your array of objects so that the product.image is a valid path.

I would suggest changing the place where the images are stored to a separate asset folder for a clearer structure instead of referring to them from the root folder

Kacper Biedka
  • 166
  • 1
  • 1
  • 9