简体   繁体   中英

Next.js - dynamic images

I'm working with next.js and trying to get images dynamically like this:

{list.map((prod) => (
      <div className={styles.singleProduct}>
          <h6>{prod.Brand.toUpperCase()}</h6>
          <p>{prod.ProductName}</p>
          <img
              src={require(`../public/assets/products/${prod.ProductName
              .replace(" ", "-")}.png`)}
           /> 
       </div>
  ))}
   

With this code I get the following error: "./public/assets/products/Product-One.png 1:0 Module parse failed: Unexpected character '�' (1:0)"

When I hard code the image everything works, f.ex.:

... 
<img
    src={require(`../public/assets/products/Product-One.png`)}
/> 
...

So I suppose that I get the error because of the dynamic variable?? Could someone help me with the issue? Thanks a lot!

I was getting the same error for svg images so I use this package https://www.npmjs.com/package/react-inlinesvg . What this package does under the hood, it loads the image url during runtime as a data uri and then convert it to image format (in this case it does svg). After converting the image it uses the image as a react component and insert it as child.

So, with the help here especially from Alvaro I finally have the solution. The following code works:

src={`/assets/products/${prod.ProductName.replace(/ /g, "-")}.png`} 

or

src={"/assets/products/" + prod.ProductName.replace(/ /g, "-") + ".png"} 

It seems as "require" doesn't work well with variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM