I'm trying to use the require()
method to paste the path to an image inside the img
tag.
This is the component. Props are passed correctly from the parent because console.log(img)
returns the correct path.
import data from '../asset/data/blog-post.json' function BlogPostFeed() { const post = data.map(item => { return <BlogPost key={item.id} img={item.img} /> }) return ( <> {post} </> ) } function BlogPost(props) { const { img } = props; return ( <> <img src={require(img)} alt="photo" /> </> ) }
This is what the json file looks like.
[ { "id": 1, "img": "../photo/photo.jpeg" } ]
I'm sure all folder paths are correct.
I tried pasting the path and it's working. However,
or
${img}
)} alt="sth"/ >
Can.
I also tried changing the json file to "img": require("../photo/photo.jpeg")
but then I got a json file error.
Popup errorCannot find module '../photo/photo.jpeg'
.
Referring to the post below, I found a simpler solution by changing the
.json
file to a.js
file. Then, as the post suggested, I converted the data to:Then in the component I just used
How to use template literals in require? (require(`${somePath}`))
This error is related to how React's underlying webpack works with the
require()
function.require()
is not a standard JavaScript function, but a functionality provided by Node.js and webpack.require()
Performs synchronous reading of modules during the build process, which means webpack needs to know the dependencies between modules at build time (before the application runs) rather than at runtime.So when you use
require("../photo/photo.jpeg")
directly, webpack knows to include this file in the build package because the path is static, not dynamic of. However, when you try to userequire(img)
, webpack doesn't know which file you're referencing until the code runs, but it's too late.In this case, I suggest two possible solutions:
This is a feature provided by modern JavaScript and webpack also supports it. Here's how you use it in your component:
Please note that you need to provide a relative path to the project root directory in the JSON file for this to work properly.
create-react-app
you can put the image into a public folder. You can then reference these images via paths relative to the public folder:Please note that in the JSON file you only need to provide the path to the public directory.