React Native NetInfo easy way to Detect Internet Connection And Display to Users 2021

In last react native tutorial we learned Rest API call using redux thunk and axios . In this tutorial we are going to use NetInfo to show an internet connection is available or not and display connection status to user.

React Native Netinfo

We are going add this feature in existing project called react-native-redux-thunk-axios-expressjs which we saw in previous week.

You can see the below example this is what we are going to create today

Netinfo Demo{ width=50% height=50% }

Let’s get started,

React native animation network status using netinfo and react native animatable

we need to install two packages @react-native-community/netinfo and react-native-animatable

npm i @react-native-community/netinfo react-native-animatable

Let’s create an InternetStatus component inside src/components folder

InternetStatus.js

import React, {useState, useEffect} from 'react';
import {Dimensions, View, Text} from 'react-native';
import NetInfo from '@react-native-community/netinfo';
import * as Animatable from 'react-native-animatable';

export default function InternetCheck() {
  const APP_NAME = 'Example App';
  const [isConnected, setIsConnected] = useState(false');
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    //Intial status
    NetInfo.fetch().then((state) => {
      setIsConnected(state.isConnected);
      if (state.isConnected == false) {
        setMounted(true);
      }
    });
    //Internet connection listener
    NetInfo.addEventListener((state) => {
      setIsConnected(state.isConnected);
      if (state.isConnected == false) {
        setMounted(true);
      }
    });
  }, []);

  return (
    <React.Fragment>
      {!isConnected && (
        <Animatable.View
          style={{
            backgroundColor: 'red',
            borderTopLeftRadius: 40,
            flexDirection: 'row',
            position: 'absolute',
            zIndex: 2,
            top: 30,
            width: Dimensions.get('window').width / 1.5,
            height: 40,
            alignItems: 'center',
            alignContent: 'center',
            alignSelf: 'center',
            borderRadius: 50,
          }}
          animation="fadeInDown">
          <View style={{flex: 2}}>
            <Text
              style={{
                color: '#fff',
                textAlign: 'center',
                alignSelf: 'center',
                fontWeight: '700',
              }}>
              You're using {APP_NAME} offline
            </Text>
          </View>
        </Animatable.View>
      )}
      {isConnected && mounted && (
        <Animatable.View
          style={{
            backgroundColor: 'green',
            borderTopLeftRadius: 40,
            flexDirection: 'row',
            position: 'absolute',
            zIndex: 2,
            top: 30,
            width: Dimensions.get('window').width / 1.5,
            height: 40,
            alignItems: 'center',
            alignContent: 'center',
            alignSelf: 'center',
            borderRadius: 50,
          }}
          animation="fadeOutUp"
          duration={5000}
          delay={2000}>
          <View style={{flex: 2}}>
            <Text
              style={{
                color: '#fff',
                textAlign: 'center',
                alignSelf: 'center',
                fontWeight: '700',
              }}>
              You're back online!
            </Text>
          </View>
        </Animatable.View>
      )}
    </React.Fragment>
  );
}

Explanation:

We imported necessary components required to display internet status to users

Next we created variable called APPNAME, this will be used in the message “You are using APPNAME offline”. This is optional one.

const [isConnected, setIsConnected] = useState(false’); this line is used to set the status of the internet connection.

const [mounted, setMounted] = useState(false); this line is just a flag to fix one issue. The issue is when a user opens the application with an internet connection our component shows the message “you are back online”.

NetInfo.fetch().then((state) => {
  setIsConnected(state.isConnected);
  if (state.isConnected == false) {
    setMounted(true);
  }
});

Netinfo.fetch() will return the status of internet connection when a user opens the app initially. Inside this, we are set the state of isConnected and mounted variables. This function executes only once but we need to monitor the internet connection runtime. We can fix that by using NetInfo.addEventListener.

NetInfo.addEventListener((state) => {
  setIsConnected(state.isConnected);
  if (state.isConnected == false) {
    setMounted(true);
  }
});

this NetInfo.addEventListner will return the status of the internet connection at run time.

Then we used two conditions two display the animated message based on the status of the internet connection. When internet is offline it shows “You’re using Example App offline”. When internet is connected it will show “You’re back online!”.

Add IneternetStatus Component inside App.js

First we need to import this inside component folder’s index.js file

import MyHeader from "./MyHeader";
import MyToast from "./MyToast";
import InternetStatus from "./InternetStatus";
export { MyHeader, MyToast, InternetStatus };

Next inside App.js add this component,

import React from "react";
import { SafeAreaView, Text } from "react-native";
import { Provider } from "react-redux";
import { applyMiddleware, createStore } from "redux";
import { rootReducer } from "./src/reducers";
import MainNavigation from "./src/navigations/MainNavigation";
import ReduxThunk from "redux-thunk";
import { InternetStatus } from "./src/components";

const store = createStore(rootReducer, {}, applyMiddleware(ReduxThunk));

const App = () => {
  return (
    <Provider store={store}>
      <SafeAreaView style={{ flex: 1 }}>
        <MainNavigation />
        <InternetStatus />
      </SafeAreaView>
    </Provider>
  );
};

export default App;

Conclusion

You can clone the code from GitHub react-native-redux-thunk-axios-expressjs. Hope you learned something new to show the internet connection status to users in a animatable way. If you have any doubts you can put them in a comment section.

Related Tutorials:

Complete Guidance to Create React Native Redux CRUD App Part 1 Complete Guidance to Create React Native Redux CRUD App Part 2 (redux setup) Complete Guidance to Create React Native Redux Example CRUD App Part 3 Complete Guidance to React Native Redux Thunk Axios Rest API Call 2021