155

I am trying to import an image file in one of my react component. I have the project setup with web pack

Here's my code for the component

import Diamond from '../../assets/linux_logo.jpg';

 export class ItemCols extends Component {
    render(){
        return (
            <div>
                <section className="one-fourth" id="html">
                    <img src={Diamond} />
                </section>
            </div>
        )
    } 
}

Here's my project structure.

enter image description here

I have setup my webpack.config.js file in the following way

{
    test: /\.(jpg|png|svg)$/,
    loader: 'url-loader',
    options: {
      limit: 25000,
    },
},
{
    test: /\.(jpg|png|svg)$/,
    loader: 'file-loader',
    options: {
      name: '[path][name].[hash].[ext]',
    },
},

PS. I can get image from any other remote source but not locally saved images. The JavaScript Console also doesn't give me any error. Please anything helps. I am quite new to react and unable to find what am I doing wrong.

5
  • 3
    Shadid, did you try <img src={require('../../assets/linux_logo.jpg')} /> ?
    – Naga Sai A
    Commented May 6, 2017 at 17:20
  • yes I tried that. Again no error in the console but I see no image
    – Shadid
    Commented May 6, 2017 at 17:29
  • 1
    You should do a webpack build and check where the images are stored. Use that path in img src.
    – vijayst
    Commented May 6, 2017 at 17:29
  • @vijayst Bless you good sir.. That worked. :)
    – Shadid
    Commented May 6, 2017 at 17:36
  • I've been struggling with this for hours. Why is it so hard to get a single logo image imported and looking right in React? It used to be so easy with plain HTML...
    – Jerry Chen
    Commented Jul 29, 2022 at 22:50

11 Answers 11

251

try using

import mainLogo from'./logoWhite.png';

//then in the render function of Jsx insert the mainLogo variable

class NavBar extends Component {
  render() {
    return (
      <nav className="nav" style={nbStyle}>
        <div className="container">
          //right below here
          <img  src={mainLogo} style={nbStyle.logo} alt="fireSpot"/>
        </div>
      </nav>
    );
  }
}
9
  • 15
    What would happen if I want to import 10 images? Commented Feb 5, 2018 at 19:06
  • 5
    @LeoGasparrini - I'm not sure I understand what you're asking-- you should be able to import as many as you wish as long as you give them unique names at import, no? Commented Mar 6, 2018 at 18:43
  • 1
    I am trying the same approach and babel is complaining as it's not able to understand what a png file is. How can I let babel skip png files from transpiling? Commented Nov 7, 2018 at 2:28
  • 2
    is possible to re export from index.ts and access multiple image like this "import { image1, image2, image3} from './../images' "??
    – ksh
    Commented Aug 9, 2020 at 18:23
  • 2
    For the curious minds out there, when we import an image like this, mainLogo is actually either a data URI (data:image/png;....) or a public URL (/static/logoWhite.svg) which dependss on your bundler. Commented Oct 24, 2020 at 16:08
20

You can use require as well to render images like

//then in the render function of Jsx insert the mainLogo variable

class NavBar extends Component {
  render() {
    return (
      <nav className="nav" style={nbStyle}>
        <div className="container">
          //right below here
          <img src={require('./logoWhite.png')} style={nbStyle.logo} alt="fireSpot"/>
        </div>
      </nav>
    );
  }
}
1
  • 1
    When I tried this solution I got this error [HMR] unexpected require(./src/components/LeftBar/home.svg) from disposed module ./src/components/LeftBar/LeftBar.js LeftBar App@http://localhost:3000/static/js/main.chunk.js:115:79 Do you know whats happen? Thank You
    – Roby Cigar
    Commented Jan 18, 2021 at 10:12
13

If the images are inside the src/assets folder you can use require with the correct path in the require statement,

var Diamond = require('../../assets/linux_logo.jpg');

 export class ItemCols extends Component {
    render(){
        return (
            <div>
                <section className="one-fourth" id="html">
                    <img src={Diamond} />
                </section>
            </div>
        )
    } 
}
7

There are few steps if we dont use "create-react-app",([email protected]) first we should install file-loader as devDedepencie,next step is to add rule in webpack.config

{
    test: /\.(png|jpe?g|gif)$/i,
    loader: 'file-loader',
}

, then in our src directory we should make file called declarationFiles.d.ts(for example) and register modules inside

declare module '*.jpg';
declare module '*.png';

,then restart dev-server. After these steps we can import and use images like in code bellow

import React from 'react';
import image from './img1.png';
import './helloWorld.scss';

const HelloWorld = () => (
  <>
    <h1 className="main">React TypeScript Starter</h1>
        <img src={image} alt="some example image" />
  </>
);
export default HelloWorld;

Works in typescript and also in javacript,just change extension from .ts to .js

Cheers.

1
  • what abut path intellisense? how to get it work?
    – Ozan Mudul
    Commented Mar 1, 2023 at 10:49
5

Create a folder and name it as images.ts or images.js in your assets folder or anywhere you wish.

Export all images in a folder using the export {default as imageName} from 'route' statement.

export { default as image1 } from "assets/images/1.png";
export { default as image2 } from "assets/images/2.png";
export { default as image3 } from "assets/images/3.png";
export { default as image4 } from "assets/images/4.png";

then import images using the import {imageDefaultName} from 'route'

import {image1,image2,image3,image4} from 'assets/images'

<img src={image1} />
<img src={image2} />
<img src={image3} />
<img src={image4} />

OR

import * as images from 'assets/images'

<img src={images.image1} />
<img src={images.image2} />
<img src={images.image3} />
<img src={images.image4} />
2
  • Cannot find module "assets/images/1.png" or its corresponding type declarations.
    – Arajay
    Commented Dec 5, 2023 at 0:02
  • Did you save the image in "assets/images/" folder? You have to save the image your own project folder and then reference it from there. Commented Dec 6, 2023 at 14:12
3

You can also try:

...
var imageName = require('relative_path_of_image_from_component_file');
...
...

class XYZ extends Component {
    render(){
        return(
            ...
            <img src={imageName.default} alt="something"/>
            ...
        )
    }
}
...

Note: Make sure Image is not outside the project root folder.

2

To dynamically import an image using a variable, you can use the following:

  const imageName = "myImage.png"
  const images = require.context('../images',true);
  const [imgUrl, setImgUrl] = useState('');

  useEffect(() => {
    if (images && imageName) {
      setImgUrl(
        images(`./${imageName}`).default
      );
    }
  }, [imageName,images]);

  ...

  <img src={imgUrl} />
1

I also had a similar requirement where I need to import .png images. I have stored these images in public folder. So the following approach worked for me.

<img src={process.env.PUBLIC_URL + './Images/image1.png'} alt="Image1"></img> 

In addition to the above I have tried using require as well and it also worked for me. I have included the images inside the Images folder in src directory.

<img src={require('./Images/image1.png')}  alt="Image1"/>
0
import React, {Component} from 'react';
import imagename from './imagename.png'; //image is in the current folder where the App.js exits


class App extends React. Component{
    constructor(props){
     super(props)
     this.state={
      imagesrc=imagename // as it is imported
     }
   }

   render(){
       return (

        <ImageClass 
        src={this.state.imagesrc}
        />
       );
   }
}

class ImageClass extends React.Component{
    render(){
        return (

            <img src={this.props.src} height='200px' width='100px' />
        );
    }
}

export default App;
0

I used user5660307 answer. And also for server-side rendering using react and nodejs, you can add this in express server:

app.use(express.static("public"));

and in webpack.client.js:

module.exports = {
  entry: "./src/client/client.js",

  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname, "public"),
  },

  module: {
    rules: [
      ...
      {
        loader: require.resolve("file-loader"),
        exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
        options: {
          name: "static/media/[name].[hash:8].[ext]",
        },
      },
      {
        test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
        loader: require.resolve("url-loader"),
        options: {
          name: "static/media/[name].[hash:8].[ext]",
        },
      },
    ],
  },
};
-2

Solved the problem, when moved the folder with the image in src folder. Then I turned to the image (project created through "create-react-app")
let image = document.createElement("img"); image.src = require('../assets/police.png');

1
  • Could be and so: import React, { Component } from 'react'; export default class Lesson3 extends Component { render() { return ( <image src={require('../assets/police.png')} /> ); } }
    – Andre
    Commented May 27, 2018 at 18:20

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