106

I have installed React using create-react-app. It installed fine, but I am trying to load an image in one of my components (Header.js, file path: src/components/common/Header.js) but it's not loading. Here is my code:

import React from 'react'; 

export default () => {
  var logo1 = (
    <img 
      //src="https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-goose.jpg"
      src={'/src/images/logo.png'}
      alt="Canvas Logo"
    />
  );
  return (
    <div id="header-wrap">
      <div className="container clearfix">
        <div id="primary-menu-trigger">
          <i className="icon-reorder"></i>
        </div>
                    
        <div id="logo">
          <a href="/" className="standard-logo" data-dark-logo='/images/logo-dark.png'>{logo1}</a>
          <a href="/" className="retina-logo" data-dark-logo='/images/logo-dark@2x.png'>
            <img src='/var/www/html/react-demo/src/images/logo@2x.png' alt="Canvas Logo" />
          </a>
        </div>
      </div>
    </div>
  );
} 

If I write the image path as src={require('./src/images/logo.png')} in my logo1 variable, it gives the error:

Failed to compile.

Error in ./src/Components/common/Header.js

Module not found: ./src/images/logo.png in /var/www/html/wistful/src/Components/common

Please help me solve this. Let me know what I am doing wrong here.

Community
  • 1
  • 1
Atul
  • 1,585
  • 5
  • 16
  • 24

11 Answers11

229

If you have questions about creating React App I encourage you to read its User Guide.
It answers this and many other questions you may have.

Specifically, to include a local image you have two options:

  1. Use imports:

     // Assuming logo.png is in the same folder as JS file
     import logo from './logo.png';
    
     // ...later
     <img src={logo} alt="logo" />
    

This approach is great because all assets are handled by the build system and will get filenames with hashes in the production build. You’ll also get an error if the file is moved or deleted.

The downside is it can get cumbersome if you have hundreds of images because you can’t have arbitrary import paths.

  1. Use the public folder:

     // Assuming logo.png is in public/ folder of your project
     <img src={process.env.PUBLIC_URL + '/logo.png'} alt="logo" />
    

This approach is generally not recommended, but it is great if you have hundreds of images and importing them one by one is too much hassle. The downside is that you have to think about cache busting and watch out for moved or deleted files yourself.

starball
  • 20,030
  • 7
  • 43
  • 238
Dan Abramov
  • 264,556
  • 84
  • 409
  • 511
  • 6
    do we really need `process.env.PUBLIC_URL`? It worked for me without `process.env.PUBLIC_URL` in react `16.8.6` – Jacob Nelson May 28 '19 at 07:44
  • Thank you Dan Abramov! --I have to note here that the React Dev Docs suggest using href="%PUBLIC_URL%/favicon.ico" -- which did NOT work for me at all. The % seems to be some sort of Webpack directive, but I'm not using Webpack... Your answer "process.env.PUBLIC_URL" worked for me perfectly--so THANK YOU!! – b0rgBart3 Oct 24 '20 at 15:25
  • 2
    You can directly provide src='/logo.png' if the image is inside public folder. – Surya Feb 08 '21 at 09:33
  • @JacobNelson the environment variable is helpful if you are hosting a react app that isn't at the root of your website, e.g. the base of your react app is `https://example.com/react/`. – code Dec 31 '21 at 02:36
  • The downside of step 1 can be alleviated (based on your situation) by creating an array of images that can be imported into a component. Import into the component that needs it. Even better is create a directory with all your images or icons and an index.js that exports that array. The actual image in the array or image object is added with require('./image-url.svg') – Justin McKee Oct 05 '22 at 14:39
36

If you want load image with a local relative URL as you are doing. React project has a default public folder. You should put your images folder inside. It will work.

enter image description here

Rivon
  • 524
  • 5
  • 5
  • 5
    This should me the accepted answer for how to locally import images – copser Nov 01 '17 at 09:42
  • 1
    I search a lot but there are very tricky solution to provide indirect way to solve it! but your solution is the best answer actually because it was the right place to keep assets. Thank you – Hamed Oct 23 '18 at 15:57
  • It is not recommended to put media in the `public` folder – Si8 Jul 30 '19 at 18:39
  • 1
    Not sure if it's recommended but if you want to dynamically display images you can use this method along with `` assuming you passed in the imgName as a param, and `imgName=exampleImage.png`, it will go to the public folder, find that image and display it – Uros Randelovic Feb 25 '21 at 19:52
  • 1
    Got this error. "You attempted to import /img/sli.jpg which falls outside of the project src/ directory. Relative imports outside of src/ are not supported." – saud00 Apr 19 '21 at 17:16
  • It is important to note that the name is CASE SENSATIVE. I created a "Public" folder, and got 404 errors until I renamed it to "public". – Max Izrin Jun 14 '22 at 08:54
11

In React or any Javascript modules that internally use Webpack, if the src attribute value of img is given as a path in string format as given below

e.g. <img src={'/src/images/logo.png'} /> or <img src='/src/images/logo.png' />

then during build, the final HTML page built contains src='/src/images/logo.png'. This path is not read during build time, but is read during rendering in browser. At the rendering time, if the logo.png is not found in the /src/images directory, then the image would not render. If you open the console in browser, you can see the 404 error for the image. I believe you meant to use ./src directory instead of /src directory. In that case, the development directory ./src is not available to the browser. When the page is loaded in browser only the files in the 'public' directory are available to the browser. So, the relative path ./src is assumed to be public/src directory and if the logo.png is not found in public/src/images/ directory, it would not render the image.

So, the solution for this problem is either to put your image in the public directory and reference the relative path from public directory or use import or require keywords in React or any Javascript module to inform the Webpack to read this path during build phase and include the image in the final build output. The details of both these methods has been elaborated by Dan Abramov in his answer, please refer to it or use the link: https://create-react-app.dev/docs/adding-images-fonts-and-files/

Pavan
  • 632
  • 5
  • 9
8

There are lot of good answers here and more expert opinions than myself. But I will just share my experience and what worked for me. I was irritated by the fact that there is so much go around just to have a simple inclusion of images. Hence here is what I did-

Create a seperate component (file) myimages.jsx

import image1 from "../img/someimage.png";
import image2 from "../img/otherimage.png";

const ImageData=[image1,image2,image3]
export default ImageData;

I then just imported this ImageData component in the file (component) I as using the images. This way I turned a cpmponent into a 'folder' to get all my images. Like I said, not an expert but this resolved my frustration with lack of importing images quickly in React.

Snowcat
  • 470
  • 8
  • 16
6

You have diferent ways to achieve this, here is an example:

import myimage from './...' // wherever is it.

in your img tag just put this into src:

<img src={myimage}...>

You can also check official docs here: https://facebook.github.io/react-native/docs/image.html

Adolfo Onrubia
  • 1,781
  • 13
  • 22
  • Thx Adolfo for ur reply, Its fine but I have around 15 images to load on the same page and define every image is not a good way I think . there should be some other way. Plz let me know If you have any idea. – Atul May 24 '17 at 10:08
  • 2
    Yep, you asked just for one. But of course if you have 1 or 100 you need to call each one anyway. I use numbered fils like img-1, img-2.... And then you can loop through an index or something like this. Example: for (let i=1; i<15; i++) { let img[i] = `./images/img-${i}` } With this you get an img[0,1,2,3... that you can manage in a better way – Adolfo Onrubia May 24 '17 at 10:13
  • thank you but this should be the extreme last approach ;) – Atul May 24 '17 at 10:19
6
In React.js latest version v17.0.1, 
we can not require the local image we have to import it.

like we use to do before = require('../../src/Assets/images/fruits.png');

Now we have to import it like = 
import fruits from '../../src/Assets/images/fruits.png';

Before React V17.0.1 we can use require(../) and it is working fine.
Arun Surawat
  • 707
  • 6
  • 8
5

In order to load local images to your React.js application, you need to add require parameter in media sections like or Image tags, as below:

image={require('./../uploads/temp.jpg')}
Ali Tourani
  • 1,170
  • 3
  • 21
  • 31
4

Instead of use img src="", try to create a div and set background-image as the image you want.

Right now it's working for me.

example:

App.js

import React, { Component } from 'react';
import './App.css';



class App extends Component {

  render() {
    return (
      <div>
        <div className="myImage"> </div>
      </div>
    );
  }
}

export default App;

App.css

.myImage {
  width: 60px;
  height: 60px;
  background-image: url("./icons/add-circle.png");
  background-repeat: no-repeat;
  background-size: 100%;
}
2

Best approach is to import image in js file and use it. Adding images in public folder have some downside:

  • Files inside public folder not get minified or post-processed,

  • You can't use hashed name (need to set in webpack config) for images , if you do then you have to change names again and again,

  • Can't find files at runtime (compilation), result in 404 error at client side.

cccn
  • 929
  • 1
  • 8
  • 20
2

First, you need to create a folder in src directory then put images you want.

Create a folder structure like

src->images->linechart.png

then import these images in JSX file

import linechart from './../../images/linechart.png'; 

then you need use in images src like below.

<img src={linechart} alt="piechart" height="400px" width="400px"></img>
aytek
  • 1,842
  • 24
  • 32
hitesh bariya
  • 97
  • 1
  • 5
0

We don't need base64, just give your image path and dimensions as shown below.

import Logo from './Logo.png' //local path
    
var doc = new jsPDF("p", "mm", "a4");
var img = new Image();
img.src = Logo;
doc.addImage(img, 'png', 10, 78, 12, 15)
bdkopen
  • 494
  • 1
  • 6
  • 16
James Siva
  • 1,243
  • 1
  • 14
  • 19
  • 1
    Please don't post only code as an answer, but include an explanation what your code does and how it solves the problem of the question. Answers with an explanation are generally of higher quality, and are more likely to attract upvotes. – Mark Rotteveel Nov 01 '19 at 12:17