Broken Image React useState

Advertisements

I’m very Junior with ReactJS, I’m trying to fix a broken image, but just don’t figure out how to fix it.

This line of code should call the image, but does not work.

<img src= {product.image + ".png"} className="max-width-400" alt='product preview'/>

But, if I add the image route, it works.

<img src= {"/img/products/" + product.image + ".png"} className="max-width-400" alt='product preview'/>

But, my teacher says that I need to create a constant or property to avoid show the /img/products/.

Thanks for your help.

>Solution :

Create (just after imports) constant field (export if needed) which holds base path to your images:

const BASE_PATH = "/img/products/";

Then use it everywhere like this:

<img src={BASE_PATH + product.image + ".png"} className=...

Leave a ReplyCancel reply