score:372

Accepted answer

when using webpack you need to require images in order for webpack to process them, which would explain why external images load while internal do not, so instead of <img src={"/images/resto.png"} /> you need to use <img src={require('/images/image-name.png')} /> replacing image-name.png with the correct image name for each of them. that way webpack is able to process and replace the source img.

score:0

i will share my solution which worked for me in a create-react-app project:

in the same images folder include a js file which exports all the images, and in components where you need the image import that image and use it :), yaaah thats it, lets see in detail

folder structure with js file

// js file in images folder
export const missing = require('./missingposters.png');
export const poster1 = require('./poster1.jpg');
export const poster2 = require('./poster2.jpg');
export const poster3 = require('./poster3.jpg');
export const poster4 = require('./poster4.jpg');

you can import in you component: import {missing , poster1, poster2, poster3, poster4} from '../../assets/indeximages';

you can now use this as src to image tag.

happy coding!

score:0

i was facing the same issue and i have figure out this solution and it works like a magic. src={${window.location.origin.tostring()}/${image name here}}

score:0

if you have your images folder inside the public folder, you need to try this:

<img src={process.env.public_url + "/images/test.jpg"}

i had the same issue and hopefully by trying this, everything just got back to normal.

when you are dealing with html & css, you can use your old method for accessing the images. but when you are in react, you are basically dealing with jsx. so this solution might be helpful for many react programmers who are struggling with loading images in react properly.

fyi:

do you remember we had a long comment in a file called index.js which was located inside our public folder? if you don't remember which comment i'm talking about, just check out the screenshot below 👇🏼:

enter image description here

i thought that it might be helpful to read it cos it's actually related to this topic and issue.

score:1

try changing the code in server.js to -

app.use(require('webpack-dev-middleware')(compiler, {
      noinfo: true,
      publicpath: config.output.path
    }));

score:1

sometimes you may enter instead of in your image location/src: try

./assets/images/picture.jpg

instead of

../assets/images/picture.jpg

score:1

src={"/images/resto.png"}

using of src attribute in this way means, your image will be loaded from the absolute path "/images/resto.png" for your site. images directory should be located at the root of your site. example: http://www.example.com/images/resto.png

score:1

here is what worked for me. first, let us understand the problem. you cannot use a variable as argument to require. webpack needs to know what files to bundle at compile time.

when i got the error, i thought it may be related to path issue as in absolute vs relative. so i passed a hard-coded value to require like below: <img src={require("../assets/images/photosnap.svg")} alt="" />. it was working fine. but in my case the value is a variable coming from props. i tried to pass a string literal variable as some suggested. it did not work. also i tried to define a local method using switch case for all 10 values (i knew it was not best solution, but i just wanted it to work somehow). that too did not work. then i came to know that we can not pass variable to the require.

as a workaround i have modified the data in the data.json file to confine it to just the name of my image. this image name which is coming from the props as a string literal. i concatenated it to the hard coded value, like so:

import react from "react";

function jobcard(props) {  

  const { logo } = props;
  
  return (
      <div classname="jobcards">
          <img src={require(`../assets/images/${logo}`)} alt="" /> 
      </div>
    )
} 
  

the actual value contained in the logo would be coming from data.json file and would refer to some image name like photosnap.svg.

score:1

i faced the same issue, and i found out the problem was the location of my images. instead of saving them into the src folder, you should store them in the public directory and have direct access.

kudos.

score:1

i resolved it this way.

so i had this issue only when i was mapping over an array with multiple images. normally with imports import artist3 from './../../../assets/images/cards_images/artists/artist3.png'; it works fine but the issue was when looping over the multiple images form an array.

i am sharing the solution that i used to approach it.

previously----- i was using imageurl: 'your_image_url.png'

now------ so in my array i changed to this imageurl: require('your_image_url.png')

  const artists = [
{firstname: 'trevor', lastname: 'bowman', imageurl: require('./../../assets/images/cards_images/artists/artist1.png') },
{firstname: 'julia', lastname: 'deakin', imageurl: require('./../../assets/images/cards_images/artists/artist2.png') },
{firstname: 'stewart', lastname: 'jones', imageurl: require('./../../assets/images/cards_images/artists/artist3.png') },
{firstname: 'arsene', lastname: 'lupin', imageurl: require('./../../assets/images/cards_images/artists/artist1.png') },

 ]

now in the other component where i used this data to loop over the artists i binded to the image src as follows

<img src={artist.imageurl.default} classname="artists__content--image br-08" alt={'img'+index} />

because when you put the require() thing you get the module object, which has a default property and it has our url (screenshot attached below)

enter image description here

so the .default thing is the extra one only to access url after using require()

score:1

  • first, check whether you have specified the current location of the image or not, if you face difficulties setting the correct path , you can use this.

  • second, import the image just like you import any js file, like this

import x from "../images/x.png";
<img src={x}/>

you can name x anything!!

score:1

ohhh yeahhh i had the same problem a few minutes ago and this worked for me:

import react from "react" import logo from "../images/logo.png"

export default function navbar() {
    return(
        <nav>
            {/* <img classname="nav--logo" src="../images/logo.png"/> */}
            <img classname="nav--logo" src={logo} alt="logo"/>
        </nav>
    ) }

score:2

i am developing a project which using ssr and now i want to share my solution based on some answers here.

my goals is to preload an image to show it when internet connection offline. (it may be not the best practice, but since it works for me, that's ok for now) fyi, i also use reacthooks in this project.

  useeffect(() => {
    // preload image for offline network
    const errorfailedimg = require('../../../../assets/images/error-review-failed.jpg');
    if (typeof window !== 'undefined') {
      new image().src = errorfailedimg;
    }
  }, []);

to use the image, i write it like this

<img src="/assets/images/error-review-failed.jpg" />

score:4

i just wanted to leave the following which enhances the accepted answer above.

in addition to the accepted answer, you can make your own life a bit easier by specifying an alias path in webpack, so you don't have to worry where the image is located relative to the file you're currently in. please see example below:

webpack file:

module.exports = {
  resolve: {
    modules: ['node_modules'],
    alias: {
      public: path.join(__dirname, './public')
    }
  },
}

use:

<img src={require("public/img/resto.ong")} />

score:4

you must import the image first then use it. it worked for me.


import image from '../image.png'

const header = () => {
   return (
     <img src={image} alt='image' />
   )
}


score:5

i too would like to add to the answers from @hawkeye parker and @kiszuriwalilibori:

as was noted from the docs here, it is typically best to import the images as needed.

however, i needed many files to be dynamically loaded, which led me to put the images in the public folder (also stated in the readme), because of this recommendation below from the documentation:

normally we recommend importing stylesheets, images, and fonts from javascript. the public folder is useful as a workaround for a number of less common cases:

  • you need a file with a specific name in the build output, such as manifest.webmanifest.
  • you have thousands of images and need to dynamically reference their paths.
  • you want to include a small script like pace.js outside of the bundled code.
  • some library may be incompatible with webpack and you have no other option but to include it as a tag.

hope that helps someone else! leave me a comment if i need to clear any of that up.

score:7

here is how i did mine: if you use npx create-react-app to set up you react, you need to import the image from its folder in the component where you want to use it. it's just the way you import other modules from their folders.

so, you need to write:

import myimage from './imagefolder/imagename'

then in your jsx, you can have something like this: <image src = {myimage} />

see it in the screenshot below:

import image from its folder in a component

score:9

use the default property:

<img src={require(`../../assets/pic-${j + 1}.jpg`).default} alt='pic' />

edit (further explanation):

require returns an object:

module {default: "/blah.png", __esmodule: true, symbol(symbol.tostringtag): "module"}

the image's path can then be found from the default property

score:18

by doing a simple import you can access the image in react

import logo from "../images/logo.png";
<img src={logo}/>

everything solved! just a simple fix =)

score:26

best way to load local images in react is as follows

for example, keep all your images(or any assets like videos, fonts) in the public folder as shown below.

enter image description here

simply write <img src='/assets/images/call.svg' /> to access the call.svg image from any of your react component

note: keeping your assets in public folder ensures that, you can access it from anywhere from the project, by just giving '/path_to_image' and no need for any path traversal '../../' like this

score:34

another way to do:

first, install these modules: url-loader, file-loader

using npm: npm install --save-dev url-loader file-loader

next, add this to your webpack config:

module: {
    loaders: [
      { test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' }
    ]
  }

limit: byte limit to inline files as data url

you need to install both modules: url-loader and file-loader

finally, you can do:

<img src={require('./my-path/images/my-image.png')}/>

you can investigate these loaders further here:

url-loader: https://www.npmjs.com/package/url-loader

file-loader: https://www.npmjs.com/package/file-loader

score:133

i started building my app with create-react-app (see "create a new app" tab). the readme.md that comes with it gives this example:

import react from 'react';
import logo from './logo.png'; // tell webpack this js file uses this image

console.log(logo); // /logo.84287d09.png

function header() {
  // import result is the url of your image
  return <img src={logo} alt="logo" />;
}

export default header;

this worked perfectly for me. here's a link to the master doc for that readme, which explains (excerpt):

...you can import a file right in a javascript module. this tells webpack to include that file in the bundle. unlike css imports, importing a file gives you a string value. this value is the final path you can reference in your code, e.g. as the src attribute of an image or the href of a link to a pdf.

to reduce the number of requests to the server, importing images that are less than 10,000 bytes returns a data uri instead of a path. this applies to the following file extensions: bmp, gif, jpg, jpeg, and png...


Related Query

More Query from same tag