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'
.
P粉7655701152023-09-10 00:43:55
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:
const data = [ { id: 1, img: require("../photo/photo.jpeg") } ] export default data;
Then in the component I just used
How to use template literals in require? (require(`${somePath}`))
P粉1557104252023-09-10 00:33:00
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 use require(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:
import React, { useState, useEffect } from 'react'; function BlogPost(props) { const { img } = props; const [imgSrc, setImgSrc] = useState(); useEffect(() => { import(`../${img}`) .then((image) => setImgSrc(image.default)) .catch((err) => console.error(err)); }, [img]); return ( <> {imgSrc && <img src={imgSrc} alt="photo" />} </> ); }
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: function BlogPost(props) { const { img } = props; return ( <> <img src={process.env.PUBLIC_URL + '/photo/photo.jpeg'} alt="photo" /> </> ); }
Please note that in the JSON file you only need to provide the path to the public directory.