Arthur K.
Arthur K.

Reputation: 142

How to display specific img on li hover without get request in react?

I have 4 boxes(<li> elements) and 4 images. Task is to show specific image when user hovers specific box. If user hovers over box 0 show image 0 if 1 show image 1.

On hover I update the state currantBox(for example currantBox: 1) and pass it to the img src attribute like so:

<img src={this.props.content[this.props.currantBox]}/>

content is a JSON array with img paths. Problem is that react on each hover ie render ie state update React makes get request to download the image, which is not efficient at all.

What is the best way to implement my idea or fix currant implementation?

Upvotes: 1

Views: 250

Answers (2)

Bill
Bill

Reputation: 3517

You could pre-load the images:

componentDidMount() {
  let loaded = 0;
  this.allLoaded = false;
  this.props.content.forEach(src => {
    var image = new Image();
    image.onLoad = function() {
      console.log('image is now loaded');
      loaded = loaded + 1;
      if (loaded === this.props.content.length) this.allLoaded = true;
    };
    image.src = src;
  }
}

With the above code, you can now check this.allLoaded before displaying anything. Note that this is a simple implementation and relies on the props never changing. If the props are expected to change after mount you may want to code something slightly more complex which accounts for that. But this should give you an idea on how to pre-load your images.

Upvotes: 1

Necvetanov
Necvetanov

Reputation: 374

If the images are not going to be changed I would suggest an entirely CSS solution. You could generate sprite with the 4 images and change the background-position property on hover.

Upvotes: 1

Related Questions