1

I am trying to pass image path via props using

require("./house.jpg");

but it gives a broken image, the path for my image is under src.

How should I pass the image path to the props in React?

const imagesrc =require("./house.jpg");

ReactDOM.render(
  <React.StrictMode>
    <Header /> 
    <HomeBanner width='100%' height='400px' alt="Banner image" src={imagesrc}  />
    <App />
  </React.StrictMode>,
  rootElement
)

File Structure

1
  • 1
    How are you consuming src prop of HomeBanner? Commented Feb 22, 2021 at 12:16

1 Answer 1

1

It's better to keep image path's in a separate file/object and export it, which would not create confusions for path and can easily be passed in props.

for example:

const ASSETS_PATH = '../assets/img/';
const IMAGE = {
  LOGO: require(ASSETS_PATH + 'logo.png'),
};

export default IMAGE;

then pass it in like this

ReactDOM.render(
  <React.StrictMode>
    <Header /> 
    <HomeBanner width='100%' height='400px' alt="Banner image" src={IMAGE.LOGO}  />
    <App />
  </React.StrictMode>,
  rootElement
)
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.