How to preload images in React.js?

How to preload images in React.js? I have a dropdown selection component that works like a menu, but I need to preload the image icons for the elements, because sometimes they are not visible the first time I open them.

I tried:

https://github.com/sambernard/react-preload

https://github.com/wizardzloy/react-img-preload

The first has a good API that is easy to understand and use, but it is an empty console with a warning that the images were not loaded, even when they were. The second one has a weird API, but I tried an example and it didn't load anything.

Therefore, I probably need to implement something myself, but I don’t know where to start. Or another option is to download them using webpack.

+12
source share
4 answers

Suppose you have pictures: string[]; - An array of URL pictures defined in your props. You need to define the componentDidMount () method in your component, and then simply create a new Image object for each image that you want to preload:

 componentDidMount() { this.props.pictures.forEach((picture) => { const img = new Image(); img.src = picture.fileName; }); } 

This forces the browser to download all images. This example is written in TypeScript.

+19
source

If it's just about delivering a few small “icons” - (why not use fonts? ) - and if the server is serving gzipped files, you can use base64, for example.

Otherwise, if the selection is not immediately displayed, you can also add img tags (with display: none ) to the previous HTML. Another way is to add image objects to the DOM and wait for .onload before displaying the component (this approach is used by the libraries you specify).

As far as I can imagine, a web package or reaction cannot do anything special for you here. This is something on the client side, and these are just tools to implement your own preload API (or even use existing APIs in JS / TS, React, Angular, ......)

+2
source

It works:

 import im1 from 'img/im1.png' import im2 from 'img/im2.png' import im3 from 'img/im3.png' componentDidMount() { imageList = [im1, im2, im3] imageList.forEach((image) => { new Image().src = image }); } 
0
source

I think the best way is to use URI data for images

 componentWillMount() { this.setState({image: "data:image/gif;base64,R0lGODlhEAAQAMQA..."}) } render() { <img src={this.state.image} /> } 
-3
source

Source: https://habr.com/ru/post/1015505/


All Articles