pallavi naik
pallavi naik

Reputation: 11

How to add images via props in ReactJs?

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

Upvotes: 1

Views: 144

Answers (1)

Syed SaeedulHassan Ali
Syed SaeedulHassan Ali

Reputation: 594

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
)

Upvotes: 1

Related Questions