React: Can't import image dynamically in reactjs

Created on 11 Dec 2019  路  12Comments  路  Source: facebook/react

Hi, I have a problem to import an image dynamically.

I have a code like this:
console.log(require("./img/item.png"));

and I want to do this:

let url = "./img/item.png";
console.log(require(url));

And it doesn't work I dont know why ?
Can someone help me ?
Thank you !

Most helpful comment

In my case I take this image from a JSON file so I define the state of my image url in the function componentWillMount() and then I call it.

componentWillMount() {
  import('./img/item.png').then(image => {this.setState({url: image})})
}
render() {
  return (
    <img src={this.state.url}/>
  )
}

All 12 comments

If you are using create-react-app you can do the following:

import itemImage from './img/item.png';

If you have a custom Webpack configuration take a look at https://webpack.js.org/loaders/file-loader/

I'm using create-react-app, but I actually want to import an image in my main function because i'm getting the url from a json file that I read in the main function so I can't import it on the top

@JeremyMeissner You can use dynamic imports for that.

e.g.:

import('./img/item.png').then(image => console.log(image));

@JeremyMeissner You can use dynamic imports for that.

e.g.:

import('./img/item.png').then(image => console.log(image));

Can I use this inside a functional component?

@JeremyMeissner , Did you find any solution for this issue or did you open any issue?

@JeremyMeissner , Did you find any solution for this issue or did you open any issue?

I used the @hristo-kanchev method

https://github.com/facebook/react/issues/17575#issuecomment-564525665

@JeremyMeissner You can use dynamic imports for that.

e.g.:

import('./img/item.png').then(image => console.log(image));

what if you don't want to console image but you want to use it in <img src={} />

In my case I take this image from a JSON file so I define the state of my image url in the function componentWillMount() and then I call it.

componentWillMount() {
  import('./img/item.png').then(image => {this.setState({url: image})})
}
render() {
  return (
    <img src={this.state.url}/>
  )
}

@JeremyMeissner Hi, with typescript I am encountering this error with your method.

Type 'typeof import("*.png")' is not assignable to type 'string'.

The url attribute of the img tag is of type string but the imported object isn't.
What am I missing?
Thank you.

Starting from CRA 4.0 this is not working anymore:
import('./img/item.png').then(image => console.log(image));
Clarification: you have to add .default. This code works like before:
import('./img/item.png').then(image => console.log(image.default));

Was this page helpful?
0 / 5 - 0 ratings

Related issues

fdecampredon picture fdecampredon  路  139Comments

iammerrick picture iammerrick  路  94Comments

gaearon picture gaearon  路  133Comments

gaearon picture gaearon  路  227Comments

gaearon picture gaearon  路  111Comments