The example given in the post work both for Android and iOS devices. So let’s go ahead below and Check Internet Connectivity in React Native.

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.

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="Check Internet Connectivity"
        />
      </View>
    );
  }
}

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

Follow me on Instagram

That’s it for now. 

If you liked this article, then please subscribe to my YouTube Channel for video tutorials.

You can also find me on Twitter and Facebook.