2

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!

13
  • Are you using a Webpack loader for images?
    – Alvaro
    Commented Nov 28, 2020 at 15:45
  • I'm using the default configuration for webpack from create-next-app. I'm new in development, so I didn't change anything. Here's a link that might help: nextjs.org/docs/api-reference/next.config.js/…
    – Ewax_Du
    Commented Nov 28, 2020 at 16:47
  • And aditionally I'm using next-images: npmjs.com/package/next-images
    – Ewax_Du
    Commented Nov 28, 2020 at 17:10
  • 1
    Could you try using strings: require("../public/assets/products/" + prod.ProductName.replace(" ", "-") + ".png")
    – Alvaro
    Commented Nov 28, 2020 at 17:43
  • 1
    Could you share next.config.js code? Not strictly related but the root element of .map is missing a key. Set one and see if it helps <div key={prod.ProductName} className={styles.singleProduct}>
    – Alvaro
    Commented Nov 28, 2020 at 18:26

2 Answers 2

0

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.

0

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.

1
  • I'm glad you could solve it. For reference, the reason for setting a known path in the begining of the require path, and possibly using string for this case is explained here.
    – Alvaro
    Commented Nov 29, 2020 at 18:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.