Import and preloading of bunch of images in React app

Pylnata
2 min readSep 17, 2019

--

https://pylnata.github.io/teddy/

During a recent development of an cartoon app with a bunch of animations and a lot of pictures(https://pylnata.github.io/teddy) that were used in those animations, I came across a couple of issues:

  1. The animation was not synchronized with the loading of pictures, and as a result the wheels were going, and the car had not yet drawn, the sun appeared before the sky, etc..
  2. Long lists of imports of images, and as a result something:

Well, as for the first problem — everything is clear: we need a standard approach with preloading images. But the second problem required a tme to find a solution, as I wanted to import all files from folder files together, not individually. And it was found thanks to the require.context from Webpack.

So, I decided to combine problem solving into one convenient mechanism, and here it is:

And as a result, we got the correct animation, fast import of the entire folder and a convenient object images to access the pictures.

In my application I made this functionality in react context to make it universal and use it for all pages. You could write hook or HOC to share logic. I hope that the article will be useful to someone.

Thank you for attention!

--

--