Creating Splash Screens In React Native

Creating Splash Screens In React Native


The first screen users view after clicking an application icon is known as a splash screen. Usually, it consists of a straightforward screen with your app’s branding in the middle that disappears when the app is ready to launch. This article will walk you through implementing a splash screen on React Native application.

Setting up React Native Project

Create React Native project if you don’t have one already. Run the following command to initialize the project:

npx react-native init splash_screen_project

You be required to switch the command line to point to the newly created directory:

cd splash_screen_project

Once done, Install the react-native-splash-screen, a library for building React Native splash screens. This library allows you to easily add splash screens for React Native apps and provides methods to control the splash screen functionalities. This includes hiding and showing the splash screen, customizing the splash screen’s appearance, and automatically hiding the splash screen after a certain period. Install it by running the following command:

#npm
npm install react-native-splash-screen
#yarn
yarn add react-native-splash-screen

To use react-native-splash-screen, you need to link the library to your project by running the following command:

rnpm link react-native-splash-screen

Finally, you can run and test your basic project development server based on your platform:

## Android
npm run android
## iOS
npm run ios

To use react-native-splash-screen, you will need to configure the native code for your platform based on iOS or Android. This includes adding code to your app’s native files, such as the AppDelegate.m file on iOS or the MainActivity.java file on Android.

Setting up Splash Screen on Android

Ensure you have Android Studio installed for Android. The project MainActivity.java file on Android will be updated as follows. The first step is to do plugin configuration. On your project android/app/src/main/java/com/splash_screen_project/MainActivity.java file, add the following configurations:

  • Add an import for the android OS bundle:
import android.os.Bundle;
  • Import the splash screen packages:
import org.devio.rn.splashscreen.SplashScreen;
import com.cboy.rn.splashscreen.SplashScreen;
  • On the onCreate() function, add the following code: This code will show the splash screen when the app is launched.
SplashScreen.show(this);

Subsequently, in the app/src/main/res/layout directory, create a launch_screen.xml file. This file will add the following for the splash screen image:

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent">
        <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:src="@drawable/launch_screen" android:scaleType="centerCrop" />
    </RelativeLayout>

Save your image asset in the android/app/src/main/res/drawable folder. It’s good to remember that launch_screen is the image asset that you want to load as the splash screen. If you change the image name, ensure this change is reflected in the launch_screen.xml file as well.

Setting up Splash Screen on IOS

To target an iOS-based platform, you must add platform-specific code configurations. Below is the iOS native code you will require so your application can load splash screens on iOS-based devices. While making these changes, ensure you have Xcode installed to run the iOS version of your app.

On the ios/SplashScreenProject/AppDelegate.m file, add the following changes:

  • Add an import for the React Native splash screen:
#import "RNSplashScreen.h"
  • On the didFinishLaunchingWithOptions, show and load the screen. Add the code just above return:
[RNSplashScreen show];

Loading the Splash Screen

The platform code is complete. To display the splash screen, you need to refactor the JavaScript code of your application, import the library, and use its APIs to control the splash screen.

These changes will go inside the src/App.tsx file as follows:

  • Import the react-native-splash-screen:
import SplashScreen from 'react-native-splash-screen'
  • Show the splash screen for 5 seconds and hide it once this time is over:
useEffect( () => {
async function prepare(){
    try{
        // our api calls will be here.
        new Promise(resolve => setTimeout(resolve,5000)); // wait for 5 secs
    }catch(e){
        console.warn(e);
    }finally{
        SplashScreen.hide();
    }
}
prepare();
});

Now you can run your platform command to test this example.

## Android
npm run android
## iOS
npm run ios

You should get the application splash screen based on the asset you used:

Session Replay for Developers

Uncover frustrations, understand bugs and fix slowdowns like never before with OpenReplay— an open-source session replay suite for developers. It can be self-hosted in minutes, giving you complete control over your customer data

Happy debugging! Try using OpenReplay today.

Creating the Splash Screen for Expo Projects

The above example requires you to use native-specific code. If you want to implement the splash screen using Expo, you must follow these steps. First, run the following command to initialize an Expo-based React Native project:

npx create-expo-app exposplashscreen

Once the installation is done, proceed to the newly created directory:

cd exposplashscreen

Install the expo-splash-screen:

npx expo install expo-splash-screen

When using Expo, you need the assets saved in the assets directory. For example, if you have hello.gif, save the image on the assets directory of the project directory.

Displaying the Splash Screen

To display Expo React Native splash screen, you need to make the following changes on your Expo project src/App.js file:

  • Import the following react-based modules:
import React,{useCallback,useEffect,useState} from 'react';
  • Import the necessary React Native modules:
import { StyleSheet, Text, View } from 'react-native';
  • Import the expo-splash-screen package:
import * as SplashScreen from 'expo-splash-screen';
  • Keep the splash screen visible using the following preventAutoHideAsync method:
SplashScreen.preventAutoHideAsync();

On the same file inside App(), add a state to check if the application is ready to be viewed:

const [appIsReady,setAppIsReady] = useState(false);

Create a useEffect() hook. This will tell React that a component needs to do something after it has been rendered. In this case, the hook will be used for viewing the splash screen for 5 secs as follows:

useEffect( () => {
    async function show_splash_screen(){
    try{
        // our api calls will be here.
        new Promise(resolve => setTimeout(resolve,5000)); // wait for 5 secs
    }catch(e){
        console.warn(e);
    }finally{
        setAppIsReady(true); // application to render.
    }
    }
    show_splash_screen();
});

Once the above time elapses, the application needs to hide this screen and allows other subsequent screens to load based on your application structure. Create the following function to hide the splash screen:

const onLayoutRootView = useCallback(async () => {
  if(appIsReady){
  // hide the splash screen.
  await SplashScreen.hideAsync();
  }
},[appIsReady]);

Avoid showing content while the splash screen is showing. To avoid showing content while the splash screen is showing, you can wrap your component tree with a loading component that only renders the main content of your app after the splash screen has been hidden.

if(!appIsReady){
    return null;
}

This approach will ensure that the application only renders the main content of your app after the splash screen has been hidden. This way, you can control when the main content is shown to the user based on your preferred setTimeout().

Create the onLayout for the application View:

return (
    <View style={styles.container} onLayout={onLayoutRootView}>
    <Text>Open up App.js to start working on your app!</Text>
    <StatusBar style="auto" />
    </View>
);

Finally, navigate to app.json and on the Expo object, define a splash as shown below:

"splash": {
    "image": "./assets/hello.gif",
    "resizeMode": "cover",
    "backgroundColor": "#FEF9B0"
}

Run the following command to start an Expo development server. This should display the splash screen based on the splash screen asset that you have used.

npm run start

Your splash screen should load once your Expo app launches for the set five seconds timeout.

Conclusion

Splash screens are considered a native feature. Following the guidelines of the platform you’re building for (iOS and Android) is essential to ensure the best user experience. This guide has helped you learn how to add a splash screen to React Native apps, using native and Expo approaches.


Originally published at blog.openreplay.com.