Import and preloading of bunch of images in React app

Pylnata
Pylnata
Sep 17, 2019 · 2 min read
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!

Pylnata

Written by

Pylnata

From backend to frontend

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade