Reputation: 2106
I noticed that, when I run the react-native
app, the images that I set as background using the tag <ImageBackground>
load with a delay of almost 2 seconds, even if they are not heavy images (~100K) and they are stored in local.
I have also read this answer but it didn't solve my problem.
This is my simple code for insert an image as background:
<ImageBackground source={require('../images/ScanQR.png')} style={styles.backgroundImage}>
<Text style={styles.domanda}>
Example text
</Text>
</ImageBackground>
Upvotes: 3
Views: 4502
Reputation: 66
Following @crodev, but for people using React Function Components, you can use hooks to achieve same result.
Additionally, you can use AppLoading component from expo-app-loading
to keep splash screen until everything is ready.
function useImages(images) {
const [loaded, setLoaded] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
Asset.loadAsync(images)
.then(() => setLoaded(true))
.catch(setError);
}, []);
return [loaded, error];
}
export default function App() {
const [imagesLoaded] = useImages([
require('./assets/images/stock1.jpg'),
require('./assets/images/stock2.jpg'),
require('./assets/images/undraw1.png'),
]);
if (!imagesLoaded) {
return <AppLoading />;
}
return <>...</>;
}
Upvotes: 0
Reputation: 1491
You can require() the images inside of App.js to load them before. Do it like this:
async function loadResourcesAsync() {
await Promise.all([
Asset.loadAsync([
require('./assets/images/stock1.jpg'),
require('./assets/images/stock2.jpg'),
require('./assets/images/undraw1.png'),
]),
Font.loadAsync({
// This is the font that we are using for our tab bar
...Ionicons.font,
// We include SpaceMono because we use it in HomeScreen.js. Feel free to
// remove this if you are not using it in your app
'open-sans-regular': require('./assets/fonts/OpenSans-Regular.ttf'),
'open-sans-extrabold': require('./assets/fonts/OpenSans-ExtraBold.ttf'),
}),
]);
}
I am using Expo here and you don't need to create this function, it's already inside of App.js, just add your images inside of require() function.
I don't know if this would work in React Native without Expo.
Upvotes: 2