How to show loading progress or spinner in the middle of the screen with React Native?

Happy Smile picture Happy Smile · Jan 29, 2020 · Viewed 29.8k times · Source

I am developing React Native app.

I was able to solve all problems by myself but this is exception. I am going to load another screen with bottom tab navigator.

For example, after user login to the app, it should show main home screen which has many pictures and many style sheet effects, icons. Because of that, after login confirm ( I mean after alert of the login confirm), the main home screen appears after a few seconds.

So I want to show some spinner in the login screen while loading main home screen in the background and when it is ready to show, erase spinner and show main home screen. How can I do this?

My bottom tab navigator was simply created with createBottomTabNavigator() method.

Answer

Akila Devinda picture Akila Devinda · Jan 29, 2020

So in your case you can do several things

  1. You can use React Native Activity Indicator -> View
  2. You can use Overlay Library -> react-native-loading-spinner-overlay -> View GitHub
  3. If you like to make loading like facebook / instagram -> then use react-native-easy-content-loader -> View GitHub

Assume that you are using React Native Activity Indicator :

import { ActivityIndicator } from "react-native";

export default class HomeScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: true
    };
  }

  //Get Home Screen Data API Action
  componentDidMount() {
    this.loadAPI(); // Call home screen get data API function
  }

  //Login API Function
  loadAPI = () => {
    this.setState({ isLoading: true }); // Once You Call the API Action loading will be true
    fetch(API_URL, {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      }
    })
      .then(response => response.json())
      .then(responseText => {
        // You can do anything accroding to your API response
        this.setState({ isLoading: false }); // After getting response make loading to false
      })
      .catch(error => {});
  };

  render() {
    return (
      <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
        {this.state.isLoading && <ActivityIndicator color={"#fff"} />}
      </View>
    );
  }
}
  • If you want to hide all the view until loading finish like images, so you can use custom library instead of Activity Indicator.