Module not found error when referencing the path for an in-directory image in React

Viewed 11

I am new to React with only about 4 months of experience, and I am facing a problem when referencing a group of images in the same directory as the code below, in order to render them on the webpage. I am getting a module not found error whenever I pass their paths from the JSON file (as an object, but still a string nevertheless) and everything works fine when I pass a single path through my function

this is the code for rendering the images one by one.

               <div className="cards col">
                    {Pagedproducts.map((item) => (
                        <div id="card" key={item.id}>
                            <div className="image">
                                <img
                                    className="prev"
                                    src={require(item.preview)}
                                    alt={"Image not rendering"}
                                />//item.preview returns a path for the image from this file's perspective
                            </div>
                        </div>
                    ))}
                </div>

using this same code but passing the path right away and rendering the same pic on all items WORKS! but i logged the item.preview variable and it literally shows the exact same path passed to the require function.

<img src={require('./productPic/IMG-1.jpg')} /> //doing this works fine but it's not what i'm trying to do

I am aware of the other methods that try to solve this but none of them use an object that holds a path to the image.

when i run my code i get a Module not found error

Uncaught Error: Cannot find module './productPic/IMG-1.jpg'

I also tried making it a string and passing the variable in it as such

<img src={require(`${item.preview}`)} />

yet also this does not work.

1 Answers

After React code is compiled, it will look into the /public directory for any images. put your photos into the public folder and it'll work.

Here is the working example. codesandbox.io

Related