I am trying to paste a path to a picture within the img
tag with the require()
method.
This is the component. Props are passed from the parent correctly because console.log(img)
return 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 am sure all the folder path are correct.
I tried to paste the path <img src={require"../photo/photo.jpeg"} alt="sth"/>
and is working. However, neither <img src={require(img)}
or <img src={require(
${img})} alt="sth"/>
would work.
I have also tried altering the json file to "img": require("../photo/photo.jpeg")
but then an error for json file comes up.
An error Cannot find module '../photo/photo.jpeg'
pops up.