409

How can I load image from local directory and include it in reactjs img src tag?

I have an image called one.jpeg inside the same folder as my component and I tried both <img src="one.jpeg" /> and <img src={"one.jpeg"} /> inside my renderfunction but the image does not show up. Also, I do not have access to webpack config file since the project is created with the official create-react-app command line util.

Update: This works if I first import the image with import img from './one.jpeg' and use it inside img src={img}, but I have so many image files to import and therefore, I want to use them in the form, img src={'image_name.jpeg'}.

Zip
  • 5,372
  • 9
  • 28
  • 39
  • 4
    Possible duplicate of [React won't load local images](http://stackoverflow.com/questions/34582405/react-wont-load-local-images) – Vanuan Oct 12 '16 at 13:11
  • See also http://stackoverflow.com/questions/37644265/correct-path-for-img-on-react-js – Vanuan Oct 12 '16 at 13:12
  • I actually have a similar issue, my image is been imported in the index.jsx file, I have the loaders in webpack, the compile face is working fine, as indeed a copy of the image is been created in my server/public/js folder with a random number, and the correct path to it is in the bundler, but I can't visualize the image. Its also strange that its been produced in the server/public/js and not server/public/img as I wrote into index.js – Carmine Tambascia Jan 10 '20 at 15:02

28 Answers28

682

First of all wrap the src in {}

Then if using Webpack; Instead of: <img src={"./logo.jpeg"} />

You may need to use require:

<img src={require('./logo.jpeg')} />


Another option would be to first import the image as such:

import logo from './logo.jpeg'; // with import

or ...

const logo = require('./logo.jpeg'); // with require

then plug it in...

<img src={logo} />

I'd recommend this option especially if you're reusing the image source.

ecraig12345
  • 2,328
  • 1
  • 19
  • 26
WillKre
  • 6,280
  • 6
  • 32
  • 62
128

The best way is to import the image first and then use it.

import React, { Component } from 'react';
import logo from '../logo.svg';
export default class Header extends Component {
  render() {
    return (
      <div className="row">
        <div className="logo">
          <img src={logo} width="100" height="50" />
        </div>
      </div>
    );
  }
} 
Marcello B.
  • 4,177
  • 11
  • 45
  • 65
Arslan shakoor
  • 1,387
  • 1
  • 9
  • 7
67

Inside public folder create an assets folder and place image path accordingly.

<img className="img-fluid" 
     src={`${process.env.PUBLIC_URL}/assets/images/uc-white.png`} 
     alt="logo"/>
barbsan
  • 3,418
  • 11
  • 21
  • 28
32

you need to use require and . default

 <img src={require('./logo.jpeg').default} />
22

You need to wrap you image source path within {}

<img src={'path/to/one.jpeg'} />

You need to use require if using webpack

<img src={require('path/to/one.jpeg')} />
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
11

put your images in the public folder or make a subfolder in your public folder and put your images there. for example:

  1. you put "completative-reptile.jpg" in the public folder, then you can access it as
src={'/completative-reptile.jpg'}
  1. you put completative-reptile.jpg at public/static/images, then you can access it as
src={'/static/images/completative-reptile.jpg'}
Martin Brisiak
  • 3,872
  • 12
  • 37
  • 51
Akshat gadhwal
  • 111
  • 1
  • 3
10

the best way for import image is...

import React, { Component } from 'react';

// image import
import CartIcon from '../images/CartIcon.png';

 class App extends Component {
  render() {
    return (
     <div>
         //Call image in source like this
          <img src={CartIcon}/>
     </div>
    );
  }
}
Abdul Moiz
  • 317
  • 3
  • 8
  • 2
    Relative imports outside of src/ are not supported. To do this you'll have to keep your images in src/, which is not recommended – toing_toing Jul 03 '19 at 09:49
  • 1
    @toing_toing Why do you not recommend keeping images in src? The official documentation has examples where this is the case: https://facebook.github.io/create-react-app/docs/adding-images-fonts-and-files – roob Jul 18 '19 at 21:07
  • 1
    increases the size of the webpack bundle and compilation time, need to recompile everytime you change an asset and increased loading time. I'd rather put it in the public folder and link by url. – toing_toing Jul 19 '19 at 13:20
  • 5
    @toing_toing You say you would 'rather....' but you don't say how to do that. – Thomas Jay Rush Dec 15 '19 at 21:09
  • @thomas-jay-rush the method to use the public folder is explained further up the page here https://stackoverflow.com/a/57291453/9594269 – mdkb Jan 25 '23 at 03:09
9

I had the same problem and after research I managed to solve it by putting the JSON data in a constant in JS, with that I was able to import the image and only inform the import in the JSON object. Example:

import imageImport from './image.png';

export const example = [
  {
    "name": "example",
    "image": imageImport
  }
]

<Image source={example.image}/>
Lucas Souza
  • 91
  • 1
  • 5
  • You are a saviour bro. I was wrapping the imported item in curly braces {} and was making them an object(unknowingly) but after I saw you answer, my problem was solved. Removed the curly braces and BOOM!! Thank you, Lucas :) – Rishav Sharma Jul 16 '22 at 10:49
8
const photo = require(`../../uploads/images/${obj.photo}`).default;
...
<img src={photo} alt="user_photo" />
Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35
natan natalin
  • 81
  • 1
  • 1
  • 4
    Please, when you answer a question try to explain what are you suggesting and why, rather than simply dropping a line of code that might or might not be understood by the OP. You might also want to refer to [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer) – secan Dec 31 '20 at 10:54
  • 1
    Hello and welcome to SO! While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. Please read the [tour](https://stackoverflow.com/tour), and [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer) – Tomer Shetah Dec 31 '20 at 11:15
7

For people who want to use multiple images of course importing them one by one would be a problem. The solution is to move the images folder to the public folder. So if you had an image at public/images/logo.jpg, you could display that image this way:

function Header() {
  return (
    <div>
      <img src="images/logo.jpg" alt="logo"/>
    </div>
  );
}

Yes, no need to use /public/ in the source.

Read further: https://daveceddia.com/react-image-tag/.

Joan Gavelán
  • 91
  • 1
  • 3
6

You have two ways to do it.

First

Import the image on top of the class and then reference it in your <img/> element like this

import React, { Component } from 'react';
import myImg from '../path/myImg.svg';

export default class HelloImage extends Component {
  render() {
    return <img src={myImg} width="100" height="50" /> 
  }
} 

Second

You can directly specify the image path using require('../pathToImh/img') in <img/> element like this

import React, { Component } from 'react'; 

export default class HelloImage extends Component {
  render() {
    return <img src={require(../path/myImg.svg)} width="100" height="50" /> 
  }
}
Community
  • 1
  • 1
Hadi Mir
  • 4,497
  • 2
  • 29
  • 31
5

If you dont want to put your image inside public folder use below syntax

 src={require("../../assets/images/img_envelope.svg").default}
4

I found another way to implement this (this is a functional component):

const Image = ({icon}) => {
   const Img = require(`./path_to_your_file/${icon}.svg`).ReactComponent;
   return <Img />
}

Hope it helps!

Kai Sheng Tung
  • 400
  • 1
  • 10
4

First you have to import the image

import logo from './logo.jpeg'; // with import

then plug it in...

<img src={logo} />

That's it.

Community
  • 1
  • 1
Shahid Hussain Abbasi
  • 2,508
  • 16
  • 10
4

I usually prefer to put images in a public folder as recommended in the official documentation.

1. Put your image into public folder. e.g, public/images/image.png
2. use directly into <img>. E.g, <img src="images/image.png" />

As it is in public folder, it will directly use those images. No need to import them.

3

As some mentioned in the comments, you can put the images in the public folder. This is also explained in the docs of Create-React-App: https://create-react-app.dev/docs/using-the-public-folder/

dyedwiper
  • 151
  • 12
3

Step 1 : import MyIcon from './img/icon.png'

step 2 :

<img
    src={MyIcon}
    style={{width:'100%', height:'100%'}}
/>    
Rahul Sarma
  • 763
  • 2
  • 8
  • 17
3

For the require method to work, I had to add ".default", like this:

<img src={require('./path/to/image.svg').default} />
Shem
  • 258
  • 2
  • 8
3

I actually just ran into this very same problem and if you move your image file from the ./public directory to the ./src directory you can import or require and either will render.

enter image description here

enter image description here

enter image description here

enter image description here

I have also tested both with the image as well as src attributes in the component and they both worked.

After I tried using the ../ to indicate the exact folder the jpg was located in I was given a usable error that allowed me to make the easy fix.

enter image description here

enter image description here the computer was kind enough to give me a usable error message.

2

My answer is basically very similar to that of Rubzen. I use the image as the object value, btw. Two versions work for me:

{
"name": "Silver Card",
"logo": require('./golden-card.png'),

or

const goldenCard = require('./golden-card.png');
{ "name": "Silver Card",
"logo": goldenCard,

Without wrappers - but that is different application, too.

I have checked also "import" solution and in few cases it works (what is not surprising, that is applied in pattern App.js in React), but not in case as mine above.

1

I have used this way, and it works... I hope you useful.

const logofooter = require('../../project-files/images/logo.png');

 return(
 <div className="blockquote text-center">
            <img src={logofooter} width="100" height="80" />
 <div/>
);
Rubzen
  • 21
  • 2
1
import React from "react";   
import image from './img/one.jpg';

class Image extends React.Component{
  render(){
    return(
      <img className='profile-image' alt='icon' src={image}/>
   );
  }
}

export default Image

Agilanbu
  • 2,747
  • 2
  • 28
  • 33
LOVENEET SINGH
  • 193
  • 2
  • 9
1

You could create a file named for instance images.js and reference all your app resources there, later importing that component in all your other component where you would need to display images

1

I wanted to import multiple images and pass them to different components. It turned out that I need to import multiple images only once and I can use them in any component by passing a prop.

import whiskey from './img/whiskey.jpg';
import hazel from './img/hazel.jpg';
import tubby from './img/tubby.jpg';

Let's make an object.

dog = [
   { name: "Whiskey", src: whiskey }, 
   // ...
]

And display the image

<img src={dog.src}></img>
1

For me, I wanted to call and use an image within an array block from an image folder. Using the "require" method and concatenating with "default" like this, solved it for me.

in my slide-data.js page:

export const sliderData = [
      {
        image:  require('../../../assets/your-image.jpg').default,
        
        desc: "simple description",
      },

You can then use e.g in a separate page, by writing

import { sliderData } from "../../slider-data";

{sliderData.map((slide, index) => {
        return (
          <div className="" key={index}>
             <img src={slide.image} alt="slide" className="image overlay " />
          </div>
        );
      })}
0
import image from './img/one.jpg';

class Icons extends React.Component{
    render(){
      return(
        <img className='profile-image' alt='icon' src={image}/>
    );
    }
}
export default Icons;
alexander.polomodov
  • 5,396
  • 14
  • 39
  • 46
Emyboy
  • 29
0

Well, you all know the answer to the question asked by now, but I am posting this answer to the question which most of you might be wondering after reading other answers:

Question: How the hell am I suppose to import 50 or 100 files:)

Answer: I suggest you make an api (.json) file and in that put the links to all the images and call the api. That's by far the best way to import files in bulk very easily, although it will take some time and knowledge, which If you don't already know.

Anuj Tanwar
  • 31
  • 1
  • 5
  • 2
    I recommend that you post your scenario as a separate question and then post your own answer. Be sure to link to this question. – ouflak Jan 21 '22 at 11:06
0

An addition, if you have multiple images to import, just and an entry point file, namely a js file the imports all the images and exports them out. Then all you have to do is import all the images from one file. What I mean is this:

Before app.js

import logo from './logo.png';
import cake from '../assets/cake.jpg';
import image from '../assets/shine.jpg';

src/imageEntry.js

import logo from './logo.png';
import cake from '../assets/cake.jpg';
import image from '../assets/shine.jpg';

export {
  logo, 
  cake, 
  image
};

After src/app.js

import { cake, logo, image} from './imageEntry.js';