1

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.

3
  • One option could be to store the image in your public folder and then you can use directly without the need for require Commented Jul 9, 2023 at 3:59
  • What do you want to achieve by using require? Why not just <img src={img} />? Commented Jul 9, 2023 at 4:25
  • Why is this tagged node.js? How are you using react, what is your build pipeline? Commented Jul 9, 2023 at 4:25

1 Answer 1

1

With reference to the following post, I have worked out a simpler solution by changing the .json file to .js file. Then, as suggested by the post, I convert the data to:

const data = [ 
  {
    id: 1,
    img: require("../photo/photo.jpeg")  
  }
]
export default data;

Then in the component, I just used <img src={img} alt="sth"/>

How to use template literals in require? (require(`${somePath}`))

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.