[javascript] Correct path for img on React.js

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.

This question is related to javascript reactjs webpack

The answer is


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

<img src={require('../logo.png')} alt="logo" className="brand-logo"/>

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="" />

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"}/> 
        )  
    }
}

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.


  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.


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" />


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} /> 

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".


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'} />

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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to webpack

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 Support for the experimental syntax 'classProperties' isn't currently enabled npx command not found where is create-react-app webpack config and files? How can I go back/route-back on vue-router? webpack: Module not found: Error: Can't resolve (with relative path) Refused to load the font 'data:font/woff.....'it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src' The create-react-app imports restriction outside of src directory How to import image (.svg, .png ) in a React Component How to include css files in Vue 2