Wednesday, August 29, 2018

Quick Tip: Images in React-Native on Android Not Loading

So something I ran into recently that I never found any good tips around.

We had a problem with static asset images not painting on Android. It appears that if there is a state-triggered repaint while the image is being spun up from a drawable, it never fully paints the image on the screen.

Typically people (read: the react-native docs) tell you to do your images something like:

<Image source={require('./my-icon.png')} />

That mostly works, but require returns a Promise and it seems like when something goes weird in the paint lifecycle stuff can go bad. There is lots of discussion out there about using the resolve asset functions from the image library, but this causes much weirdness between the debug and release variants of your app. You can do Promise.all([]) from UNSAFE_componentWillMount. But there is an easier way!

import myIcon from './my-icon.png';

Why is this better than const myIcon = require('./my-icon.png')? Well import still does the same thing under the hood that require() does. The difference is import demands that all the required things are fully resolved before it begins evaluating the the script at all. This means that your image assets are guaranteed to be loaded before the script evaluates. Lemon squeezy.


1 comment: