232

I have some problem with my images on my react project. Indeed I always thought that relative path into src attribute was built on the files architecture

Here my files architecture:

components
    file1.jsx
    file2.jsx
    file3.jsx
container
img
js 
... 

However I realized that the path is built on the url. In one of my component (for example into file1.jsx) I have this:

localhost/details/2
<img src="../img/myImage.png" /> -> works

localhost/details/2/id
<img src="../img/myImage.png" /> -> doesn't work, images are not displayed

How is it possible to solve this problem? I want that in any form of routes handled by react-router, all images can be displayed with the same path.

3
  • 2
    just point directly to the image, dont use ../ whatever
    – omarjmh
    Commented Jun 5, 2016 at 16:47
  • 5
    You need to use require. Read this answer on SO for more info.
    – today
    Commented Apr 23, 2018 at 12:15
  • Hope this answer helps you out React local images
    – Mokesh S
    Commented May 13, 2020 at 19:47

14 Answers 14

477

In create-react-app relative paths for images don't seem to work. Instead, you can import an image:

import logo from './logo.png' // relative path to image 

class Nav extends Component { 
    render() { 
        return ( 
            <img src={logo} alt={"logo"}/> 
        )  
    }
}
8
  • 55
    what about dynamic images, for instance, referenced in a json file, in create-react-app?
    – zok
    Commented May 2, 2017 at 14:47
  • 2
    @zok I think you would export the variable from the JSON file, import the variable into your component. Then you can reference it as usual. e.g. export const my_src = variable_here, import {my_src} from my_file, and src={my_src}. Commented May 3, 2017 at 20:30
  • 2
    import './styles/style.less'; **import logo from './styles/images/deadline.png';** I am getting error on 2nd line module not found while image exists & path is correct.
    – Hitendra
    Commented Jun 22, 2017 at 20:52
  • This method is also confirmed by by survive.js if you want to take a look at one of the core webpack author's methods. He also mentions you can use babel-plugin-transform-react-jsx-img-import to get around having to import the image every time you reference an image.
    – a_dreb
    Commented Mar 21, 2018 at 23:11
  • 2
    Not this, it solves only image issue but does not solve the path issue.. Dima Gershman' answer is the actual react solution for path of any file img or else
    – Sami
    Commented Apr 9, 2018 at 8:39
231

If you used create-react-app to create your project then your public folder is accessible. So you need to add your image folder inside the public folder.

public/images/

<img src="/images/logo.png" />

2
  • 4
    It worked for me. Just remember that you need to restart the app if you added new image to the public directory.
    – awasik
    Commented Nov 4, 2019 at 11:41
  • It is indeed a fast way to treat the situations, but it will work only if you don't need relative URLs. E.g. if you serve your app at www.example.com/react-app, the public folder will be exposed on www.example.com, without react-app. This can be troublesome, so the accepted answer is the correct one. Sources: adding assets and using public folder Commented Apr 27, 2020 at 17:42
99

You're using a relative url, which is relative to the current url, not the file system. You could resolve this by using absolute urls

<img src ="http://localhost:3000/details/img/myImage.png" />

But that's not great for when you deploy to www.my-domain.bike, or any other site. Better would be to use a url relative to the root directory of the site

<img src="/details/img/myImage.png" />

7
  • 5
    Thanks, I would emphasize the / that precedes details (vs ./details, etc, for others who may conflate the two). Commented Dec 30, 2016 at 17:39
  • 2
    Even for me it's not working. I am using reactjs with cordova and using ES5 as eslint Commented May 8, 2018 at 7:19
  • 2
    While both this and claireablani's solution work, claireablani's is what the create-react-app docs recommend. They list a number of benefits over putting the resources in public facebook.github.io/create-react-app/docs/… Commented Jan 22, 2019 at 18:56
  • @user1322092 is right. Remember it's /images/popcorn.png and not ./images/popcorn.png. Worked for me with all the routes and stuff.
    – Nuhman
    Commented Jun 22, 2019 at 5:54
  • 1
    like @Dima mentioned below, if you used create-react-app then you can place the images in public->myImgFolder->myImg.png folder and use it as <img src="/myImgFolder/myImg.png" alt={"logo"}/> Commented Jun 7, 2021 at 22:28
76

With create-react-app there is public folder (with index.html...). If you place your "myImage.png" there, say under img sub-folder, then you can access them through:

<img src={window.location.origin + '/img/myImage.png'} />
4
  • 8
    This should be marked as the correct answer, because it is actually reactjs solution for all types of paths of any files
    – Sami
    Commented Apr 9, 2018 at 8:41
  • I don't understand why you think this is the correct answer. I just tried this answer and Claireblani's answer and claire's answer worked while this did not. This answer only works if the image is in the public folder. Should my images go in the public folder? @Sami
    – Maderas
    Commented Aug 15, 2018 at 4:00
  • Yes @Maderas first things is is this answer is same as the accepted one => just removing {} and base url you can use simply src='/relative path of image' or src='absolute path of image' Whats more in this answer is that it accommodates variable path for any image
    – Sami
    Commented Aug 15, 2018 at 6:26
  • So far works for me like a charm. Nothing else did! And I tried just about everything. Thanks! Commented Mar 30, 2020 at 5:08
48

If the image is placed inside the 'src' folder, use the following:

<img src={require('../logo.png')} alt="logo" className="brand-logo"/>
3
  • 2
    That worked for me. This works in the case you DON'T want to store images in public folder Commented Jul 18, 2020 at 5:47
  • 2
    For anyone facing [object Module] error in the img's src, do this src={require('../logo.png').default}
    – nimsrules
    Commented Feb 23, 2022 at 18:20
  • 1
    This works for .csv files as well. A great help. Commented Jun 29, 2022 at 10:23
41
  1. Make an images folder inside src(/src/images) And keep your image in it. Then import this image in your component(use your relative path). Like below-

    import imageSrc from './images/image-name.jpg';

    And then in your component.

    <img title="my-img" src={imageSrc} alt="my-img" />

  2. Another way is to keep images in public folder and import them using relative path. For this make an image folder in public folder and keep your image in it. And then in your component use it like below.

    <img title="my-img" src='/images/my-image.jpg' alt="my-img" />

    Both method work but first one is recommended because its cleaner way and images are handled by webpack during build time.

3
  • This won't work, a slash ( / ) is required at the start to indicate relative path, like so: "/images/pitbull-mark.png"
    – Jeremy Rea
    Commented Apr 23, 2019 at 13:07
  • have you tried the one mentioned in the answer? This should work too.
    – Mustkeem K
    Commented Apr 24, 2019 at 4:54
  • @JeremyRea A slash at the start indicates an absolute path, not a relative path.
    – kojow7
    Commented Jan 9, 2021 at 21:56
21

Some older answers din't work, others are good but won't explain the theme, in summary:

If image is in 'public' directory

Example: \public\charts\a.png

In html:

<img id="imglogo" src="/charts/logo.svg" />

In JavaScript:

Create image to new img, dynamically:

var img1 = document.createElement("img");  
img1.src = 'charts/a.png';  

Set image to existing img with id as 'img1', dynamically:

document.getElementById('img1').src = 'charts/a.png';

If image is in 'src' directory:

Example: \src\logo.svg

In JavaScript:

import logo from './logo.svg';  
img1.src = logo;  

In jsx:

<img src={logo} /> 
10

I have used it this way and it worked perfectly

import Product from "../../images/product-icon.png";
import { Icon } from "@material-ui/core";

<Icon>
    <img src={Product} style={{ width: "21px", height: "24px" }} />
</Icon>
5

Adding file-loader npm to webpack.config.js per its official usage instruction like so:

config.module.rules.push(
    {
        test: /\.(png|jpg|gif)$/,
        use: [
            {
                loader: 'file-loader',
                options: {}
            }
        ]
    }
);

worked for me.

0
3

Import Images in your component

import RecentProjectImage_3 from '../../asset/image/recent-projects/latest_news_3.jpg'

And call the image name on image src={RecentProjectImage_3} as a object

 <Img src={RecentProjectImage_3} alt="" />
2

A friend showed me how to do this as follows:

"./" works when the file requesting the image (e.g., "example.js") is on the same level within the folder tree structure as the folder "images".

1

Place the logo in your public folder under e.g. public/img/logo.png and then refer to the public folder as %PUBLIC_URL%:

<img src="%PUBLIC_URL%/img/logo.png"/>

The use of %PUBLIC_URL% in the above will be replaced with the URL of the public folder during the build. Only files inside the public folder can be referenced from the HTML.

Unlike "/img/logo.png" or "logo.png", "%PUBLIC_URL%/img/logo.png" will work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running npm run build.

0

If your page url contains multiple / then in src go back / count minus 1 times.

For example page url http://localhost:3000/play/game/ then src url must be ../your-image-folder/image-name. And your your-image-folder must be in public folder.

0

I create my app with create-react-app and I use require instruction if I want to change dynamically my image src:

export const MyComponent = () => {
  const [myImg, setMyImg] = useState(require('./path/to/my/img'));

  const handleClick = () => {
    setMyImg(require('./path/to/other/img'));
  }

  return (
    <div>
      <img src={myImg} alt='myImg' />
      <button onClick={handleClick}>Click me!<button/>
    <div>
  )
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.