Detect if the user is connected to the internet in React-native

User Experience is one of the things that makes the user like an app. The better the experience, the happier the customer.

One area of User Experience is about connectivity to the internet. Let’s say the user is not connected to the internet. And sending the API request again and again. But there is neither any response nor any error. This makes the user wonder if the app is even responding or not.

To avoid such scenario, we can implemented a top (or bottom) bar item to address that the user is still connected or not.

Let’s see how we can do this in react-native.

Create a new project

use the following command to setup a new project and run it.

We are going to require another package for it i.e NetInfo, so that we can track the network connection.

npx react-native init DemoProject
cd DemoProject
npm install --save @react-native-community/netinfo
react-native run-android

Create new file as TopBar.js

And add the code below. Here we are creating a component, with the useState hook of isConnected.

If the internet is Connected, we will see a Green bar with text ‘Connected’, else a Red Bar with text ‘No Internet Connection’.

import React, {useState, useEffect} from 'react';
import {View, Text, StyleSheet} from 'react-native';
import NetInfo from '@react-native-community/netinfo';

export const TopBar = () => {
  const [isConnected, setIsConnected] = useState(true);

  if (isConnected) {
    return (
      <View style={[styles.container, {backgroundColor: 'green'}]}>
        <Text style={styles.text}> Connected</Text>
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <Text style={styles.text}> No Internet Connection</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: 'red',
    alignItems: 'center',
  },
  text: {
    color: 'white',
  },
});

and import it into the main App.js file like below.

import React from 'react';
import {View} from 'react-native';
import {TopBar} from './TopBar';

const App = () => (
  <View>
    <TopBar />
  </View>
);

export default App;

Initially we will be only seeing the ‘connected’ message.

Add the connection logic

As we already installed NetInfo package to our project. We need to create the event listener in TopBar.js to detect the connection change. Once component is unmounted, we will unsubscribe to this event.

import NetInfo from '@react-native-community/netinfo';

export const TopBar = () => {
  const [isConnected, setIsConnected] = useState(true);

  useEffect(() => {
    const unsubscribe = NetInfo.addEventListener((state) => {
      setIsConnected(state.isConnected);
    });
    return () => {
      unsubscribe();
    };
  }, []);

That’s all. Now you can detect the network connection change in the event listener.

Hope you like this post. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *