How to Check Internet Connectivity in React Native (Android and iOS)

Last Updated on November 2, 2018.

Most of the mobile apps in the market use internet to provide services. Hence listening to internet connectivity changes is very important to make the user aware about the situation.

In react native NetInfo api is used to test whether the Internet is connected or not. Checking internet connectivity in Android and iOS are different. So you have to use platform specific code to check internet connectivity in both OS.

The example given below check internet connectivity when the button is pressed and it gives corresponding Alert messages.

import React, { Component } from "react";
import { View, Text, Button, Alert, NetInfo, Platform } from "react-native";

export default class componentName extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  CheckConnectivity = () => {
    // For Android devices
    if (Platform.OS === "android") {
      NetInfo.isConnected.fetch().then(isConnected => {
        if (isConnected) {
          Alert.alert("You are online!");
        } else {
          Alert.alert("You are offline!");
        }
      });
    } else {
      // For iOS devices
      NetInfo.isConnected.addEventListener(
        "connectionChange",
        this.handleFirstConnectivityChange
      );
    }
  };

  handleFirstConnectivityChange = isConnected => {
    NetInfo.isConnected.removeEventListener(
      "connectionChange",
      this.handleFirstConnectivityChange
    );

    if (isConnected === false) {
      Alert.alert("You are offline!");
    } else {
      Alert.alert("You are online!");
    }
  };

  render() {
    return (
      <View>
        <Button
          onPress={() => this.CheckConnectivity()}
          title="Check Internet Connectivity"
          color="#841584"
          accessibilityLabel="Learn more about this purple button"
        />
      </View>
    );
  }
}

3 thoughts on “How to Check Internet Connectivity in React Native (Android and iOS)”

  1. I have tested, but the problem this not check your internet connection, only the wifi. If you are connected by wifi, but not have internet in your router, the NETInfo will return true.

    1. Bruno de Oliveira

      That’s why a good idea would be to “ping” some endpoint in a API rest, maybe create a api.host.com/healthcheck to access and get the return parameters.

  2. Pingback: How to check internet connection in React Native application for both iOS and Android? – inneka.com

Leave a Reply

%d bloggers like this: