0

I want to dynamically render images, but nothing is show up. Here is the starter code that I am using from Import image dynamically in React component.

import React, { Component, Fragment } from 'react';

class Test extends Component{
    constructor(props){
        super(props);
        this.state = {
            image: "",
        }
        this.loadImage = this.loadImage.bind(this);
    }
    componentDidMount(){
        this.loadImage("Test")
    }
    loadImage = imageName => {
        import(`../assets/${imageName}.png`).then(image => {
          this.setState({
            image
          });
        });
      };
      render() {
        const { image } = this.state;
        return (
          <Fragment>
              hello
            {image && <img src={image} alt="" />}
          </Fragment>
        );
      }
}

export default Test;

Hello renders, but the image is no where to be seen. Any thoughts

1 Answers1

0

You can add the string directly into your image state, without rendering it asynchronous. I don't think the import statement is needed. Once you have the string you could use a similar logic you have already in place with the image but instead if you are using webpack this might work:

<div
    style={{
      backgroundImage: `url(${image})`,
      height: "106px"
    }}

If you are not using webpack, than you can add the image state in the src attribute.

Noah Kanyo
  • 500
  • 1
  • 3
  • 8
  • I am new to react and am using the create-react-app. I have previously used the solution that you posted, but it doesn't work for me. However, only when I put the style in the corresponding css file does the image render. The URL is static obviously. I am not sure what I am doing wrong. The only way I have gotten images to show is using the import x from "../test.png" (example) at the top of the file where you have the other import statements. Do you know what I am doing wrong here? – ENDGAMEPROPHECY Jan 20 '21 at 22:18
  • If you are importing static assets you got it right, dynamic assets are a bit trickier, especially if you are using webpack which forces developers to use require('./img') inside the img src attribute to image on load. Rendering the image via css is the easiest way to deal with dynamic images. – Noah Kanyo Jan 21 '21 at 09:43