Alvin Lee
Alvin Lee

Reputation: 47

How to preload local images?

I am trying to preload all these images before I start my navigation other screens. But I'm not sure how to implement it. Please help..

import React from "react";
import { Provider } from "react-redux";
import navigationServices from "./src/helper/navigationServices";
import store from "./src/redux/store";
import RootNavigation from "./src/rootNavigation";


const images = [
  require('./assets/icons/back.png'),
  require('./assets/icons/plants.png'),
  require('./assets/icons/seeds.png'),
  require('./assets/icons/flowers.png'),
  require('./assets/icons/sprayers.png'),
  require('./assets/icons/pots.png'),
  require('./assets/icons/fertilizers.png'),
  require('./assets/images/plants_1.png'),
  require('./assets/images/plants_2.png'),
  require('./assets/images/plants_3.png'),
  require('./assets/images/explore_1.png'),
  require('./assets/images/explore_2.png'),
  require('./assets/images/explore_3.png'),
  require('./assets/images/explore_4.png'),
  require('./assets/images/explore_5.png'),
  require('./assets/images/explore_6.png'),
  require('./assets/images/illustration_1.png'),
  require('./assets/images/illustration_2.png'),
  require('./assets/images/illustration_3.png'),
  require('./assets/images/avatar.png'),
];

const App = () => (
  <Provider store={images}>
    <RootNavigation
      ref={navRef => navigationServices.setTopLevelNavigator(navRef)}
    />
  </Provider>
);

export default App;

I tried to place the const images into the Provider from redux but it couldnt load

Upvotes: 3

Views: 3875

Answers (2)

MDB
MDB

Reputation: 131

List of images to preload:

// Preload images with require();
const images = {
  'icon.png': require('./icon.png'),
  'orbs-1.png': require('./orbs-1.png'),
  'orbs-2.png': require('./orbs-2.png'),
  'orbs-3.png': require('./orbs-3.png'),
  'survey-1.png': require('./survey-1.png'),
};

Image processor:

// Convert image refs into image objects with Image.resolveAssetSource
loadImages(images) {        
    return Promise.all(Object.keys(images).map((i) => {
        let img = {
            ...Image.resolveAssetSource(images[i]),
            cache: 'force-cache'
        };

        return Image.prefetch(img);
    }));
}

Usage:

loadImages(images).then((results) => { /* do something with the image objects */ });

Upvotes: 0

Damian Busz
Damian Busz

Reputation: 1848

The best option would be if you preload them in componentDidMount or useEffect hook.

import avatar from 'assets/avatar.png'
import plants from 'assets/plants.png'
import seeds from 'assets/seeds.png'

useEffect(() => {
  imageList = [avatar, plants, seeds]
  imageList.forEach((image) => {
    new Image().src = image
  });
}, [])

Upvotes: 2

Related Questions