Import image dynamically in React component Import image dynamically in React component reactjs reactjs

Import image dynamically in React component


I used context.

const images = require.context('../../../assets/img', true);loadImage = imageName => (assets(`./${imageName}`).default);<img src={loadImage("someimage.png")} alt="" />

I don't know if this is an optimal solution, but it works.


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>  );}

View Codesandbox Demo

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  )}