DEV Community

Discussion on: Image Relative Path in React

Collapse
 
sirajrkhan profile image
Siraj Khan • Edited

Thanks a lot Sofia for detailed blog. I also faced same thing when I started, and honestly it was quite frustrating.

At that time below solution bailed me out:

    import sea from './images/sea.jpg';
    import sunset from './images/sunset.jpg';

   <img src={sunset} alt="Sunset View on Beach" />
Enter fullscreen mode Exit fullscreen mode

Your solution is also great... the only suggestion I would make is.. if we can set a variable, where we define the folder path, it would help avoiding repetition. Example:

const IMG_PATH = './images/'
<img src={require(`${IMG_PATH}sea.jpg`)} alt="Sea and mountain" />
Enter fullscreen mode Exit fullscreen mode

or even better:

const IMG = (imgName) => {
  return require(`./images/${imgName}`)
}
<img src={IMG("sunset.jpg")} alt="Sunset View on Beach" />
Enter fullscreen mode Exit fullscreen mode