Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preload an image from local in react native with Expo

I'm doing a project but i'm stuck when loading a background image.

<Image
    source={Images.welcomeBg}
    style={styles.container}
  >
...
</Image>

But Image spends 1-2 second to load it I'm doing follow this link It still doesn't work right now. Plz help me fix this bug enter image description here

like image 695
Hoai Truong Avatar asked Oct 27 '25 09:10

Hoai Truong


1 Answers

you can do this

make new called cachedAssetAsync.js (sure you can choose whatever name you like)

import { Asset, Font } from 'expo';

export default function cacheAssetsAsync({
  images = [],
  fonts = [],
  videos = [],
}) {
  return Promise.all([
    ...cacheImages(images),
    ...cacheFonts(fonts),
    ...cacheVideos(videos),
  ]);
}

function cacheImages(images) {
  return images.map(image => Asset.fromModule(image).downloadAsync());
}

function cacheVideos(videos) {
  return videos.map(video => Asset.fromModule(video).downloadAsync());
}

function cacheFonts(fonts) {
  return fonts.map(font => Font.loadAsync(font));
}

then in App.js or whatever your root component you use, can do like this

  async _loadAssetsAsync() {
    try {
      await cacheAssetsAsync({
        images: [require('./assets/images/exponent-icon.png')],
        fonts: [
          { 'space-mono': require('./assets/fonts/SpaceMono-Regular.ttf') },
          MaterialIcons.font,
        ],
        videos: [require('./assets/videos/ace.mp4')],
      });
    } catch (e) {
      console.log({ e });
    } finally {
      this.setState({ appIsReady: true });
    }
  }

you can do the logic when appIsReady is false shows loading screen then when appIsReady is true show the actual screen. And sure you can do this in only one file.

expo doc: https://docs.expo.io/versions/latest/guides/preloading-and-caching-assets.html

like image 86
2r83 Avatar answered Oct 29 '25 06:10

2r83