How to use onload in react?

Instead of rendering the image which you dont want, you could simply load it in componentDidMount like

class PicturesList extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
      imagesarray: []
      };
      this.imagestore = this.imagestore.bind(this);
    }

    componentDidMount() {
       const img = new Image();
        img.onload =() => {
          // image  has been loaded
          this.imagestore()
        };

        img.src = 'image_7.jpg';
    }
    render() {
       return (
          <div>
            </div>
            <Gallery url={this.state.imagesarray}/>
          </div>
       );
    }
    imagestore() {
        const imgUrls=this.props.apikeys;
        const objarr = Object.values(imgUrls);
        this.setState({
            imagesarray: objarr
        });
    }

}

The above solution is just to call imageStore once an image is loaded. However if what you intend is to call imageStore when the component has fully loaded,just trigger this.imageStore() in componentDidMount

class PicturesList extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
      imagesarray: []
      };
      this.imagestore = this.imagestore.bind(this);
    }

    componentDidMount() {
        this.imagestore()
    }
    render() {
       return (
          <div>
            </div>
            <Gallery url={this.state.imagesarray}/>
          </div>
       );
    }
    imagestore() {
        const imgUrls=this.props.apikeys;
        const objarr = Object.values(imgUrls);
        this.setState({
            imagesarray: objarr
        });
    }

}

Leave a Comment