Import image dynamically in React component
You can load images dynamically from the API response with dynamic imports
that is Stage 3 proposal as of now.
The resulting code should look something like:
loadImage = imageName => { import(`./assets/${imageName}.jpg`).then(image => { this.setState({ image }); });};render() { const { image } = this.state; return ( <Fragment> {image && <img src={image} alt="" />} </Fragment> );}
This feature is supported out of the box in create-react-app
, If using other systems, you can use the Babel plugin
there are my way, works nicely:)
import React, {useState} from "react"const getFavorites = (props) => { const {item, favouritesNote} = props; const [image, setImage] = useState(""); (function (imageName) { import( `../../../../assets/images/chart/favorite${imageName ? "_active" : ""}.png` ).then((image) => setImage(image.default)); })(favouritesNote[item.id]); return ( <div>{image && <img alt="" className="img-responsive" src={image} />}</div )}