Sunday, August 18, 2019

React Native NetInfo Example to Detect Internet Connection

This tutorial explains how to detect internet connection status using Netinfo library in react native application. React Native NetInfo exposes information about online/offline status. NetInfo notifies continuously about the network state whether it is online or offline. React Native’s NetInfo component is used to check internet connectivity status runtime in react native application. NetInfo is properly works in both android and iOS mobile platforms. Using the NetInfo component we can detect networks status like your mobile is connected to active internet connection or not and also which connection type your mobile phone is using 4G, 3G, 2G and WiFi. In this tutorial we would going to make a react native application with NetInfo Example to Detect Internet Connection in Live App mobile application in both android and iOS platforms. We are going to use react-native-netinfo library in order to check internet connection status.

React Native NetInfo Example to Detect Internet Connection


Installation of Dependency

Install the react-native-netinfo library using below command :
npm install --save @react-native-community/netinfo

Screenshot for reference : 

You then need to link the native parts of the library for the platforms you are using. The easiest way to link the library is using the CLI tool by running this command from the root of your project:
react-native link @react-native-community/netinfo

Screenshot for reference : 

You need to put the ACCESS_NETWORK_STATE permission in AndroidManifest.xml file
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


React Native NetInfo

In this example we are going to check the internet connection status like device is connected to internet or not and according we will display the connection status on application screen with online and offline status text. Lets see the complete source code that helps to detect internet connection status using Netinfo library in react native application.

Step 1: Create a new react native project, if you don’t know how to create a new project in react native just follow this tutorial.

Step 2: Open App.js File in your favorite code editor and erase all code and follow this tutorial.

Step 3: Lets install the react-native-netinfo library in your react native project.
Install the react-native-netinfo library using below command :
npm install --save @react-native-community/netinfo

Link the dependency using below command :
react-native link @react-native-community/netinfo

You need to put the ACCESS_NETWORK_STATE permission in AndroidManifest.xml file. goto YourReactNativeProject -> android -> app -> src -> main -> AndroidManifest.xml and place the below permission inside it.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Step 4: Through react , react-native packages, react-native-netinfo  import all required components.
import React, { Component } from 'react';
import { StyleSheet, Text, View   } from 'react-native';
import NetInfo from '@react-native-community/netinfo'

Step 5: Lets create constructor block inside your App component. In the constructor block we have created state variables named as connection_Status.
constructor() {
    super();
    this.state = {
      connection_Status: ""
    }
  }

Step 6: Lets create componentDidMount and componentWillUnmount lifecycle method, that helps to detect internet connection using event listener function.
componentDidMount() {
    NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectivityChange);

    NetInfo.isConnected.fetch().done((isConnected) => {
      if (isConnected == true) {
        this.setState({ connection_Status: "Online" })
      }
      else {
        this.setState({ connection_Status: "Offline" })
      }
    });
  }

  componentWillUnmount() {
    NetInfo.isConnected.removeEventListener('connectionChange', this.handleConnectivityChange);
  }

  handleConnectivityChange = (isConnected) => {
    if (isConnected == true) {
      this.setState({ connection_Status: "Online" })
    }
    else {
      this.setState({ connection_Status: "Offline" })
    }
  };

Step 7: Implement render method inside the App class and wrapped the below layout design inside the root View component.  
render() {
    return (
      <View style={styles.container}>
        <Text style={styles.text}> Device Current Status :  </Text>
        <Text style={styles.text}> You are {this.state.connection_Status} </Text> 
      </View>
    );
  }

Step 8 : Apply the below style sheet design. 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  text: {
    fontSize: 18,
    color: 'black',
  },
});

Complete Source Code for App.js 

Lets see the complete source code that helps to detect internet connection status using Netinfo library in react native application.

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


export default class App extends Component {

  constructor() {
    super();
    this.state = {
      connection_Status: ""
    }
  }

  componentDidMount() {
    NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectivityChange);

    NetInfo.isConnected.fetch().done((isConnected) => {
      if (isConnected == true) {
        this.setState({ connection_Status: "Online" })
      }
      else {
        this.setState({ connection_Status: "Offline" })
      }
    });
  }

  componentWillUnmount() {
    NetInfo.isConnected.removeEventListener('connectionChange', this.handleConnectivityChange);
  }

  handleConnectivityChange = (isConnected) => {
    if (isConnected == true) {
      this.setState({ connection_Status: "Online" })
    }
    else {
      this.setState({ connection_Status: "Offline" })
    }
  };

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.text}> Device Current Status :  </Text>
        <Text style={styles.text}> You are {this.state.connection_Status} </Text> 
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  text: {
    fontSize: 18,
    color: 'black',
  },
});

Screenshot : 

React Native NetInfo Example to Detect Internet Connection

React Native NetInfo Example to Detect Internet Connection

This is all about React Native NetInfo Example to Detect Internet Connection. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.


No comments:

Post a Comment