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 !
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));
Please file this issue at https://github.com/facebook/create-react-app/issues
@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.
@sh4nnongoh Hi, did you try this ?
https://stackoverflow.com/questions/51100401/typescript-image-import#51163365
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));
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.