npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2019 – Ryan Hefner

@react-native-community/netinfo

v4.6.1

Published

React Native Network Info API for iOS & Android

Downloads

479,900

Readme

@react-native-community/netinfo

CircleCI Status Supports Android, iOS, and Windows MIT License Lean Core Extracted

React Native Network Info API for Android, iOS & Windows. It allows you to get information on:

  • Connection type
  • Connection quality

Getting started

Install the library using either Yarn:

yarn add @react-native-community/netinfo

or npm:

npm install --save @react-native-community/netinfo

Using React Native >= 0.60

Linking the package manually is not required anymore with Autolinking.

  • iOS Platform:

    $ cd ios && pod install && cd .. # CocoaPods on iOS needs this extra step

  • Android Platform with Android Support:

    Using Jetifier tool for backward-compatibility.

    Modify your android/build.gradle configuration:

    buildscript {
      ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
        # Only using Android Support libraries
        supportLibVersion = "28.0.0"
      }
  • Android Platform with AndroidX:

    Modify your android/build.gradle configuration:

    buildscript {
      ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
        # Remove 'supportLibVersion' property and put specific versions for AndroidX libraries
        androidXCore = "1.0.2"
        // Put here other AndroidX dependencies
      }

Using React Native < 0.60

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

If you can't or don't want to use the CLI tool, you can also manually link the library using the instructions below (click on the arrow to show them):

Manually link the library on iOS

Either follow the instructions in the React Native documentation to manually link the framework or link using Cocoapods by adding this to your Podfile:

pod 'react-native-netinfo', :path => '../node_modules/@react-native-community/netinfo'
Manually link the library on Android

Make the following changes:

android/settings.gradle

include ':react-native-community-netinfo'
project(':react-native-community-netinfo').projectDir = new File(rootProject.projectDir, '../node_modules/@react-native-community/netinfo/android')

android/app/build.gradle

dependencies {
   ...
   implementation project(':react-native-community-netinfo')
}

android/app/src/main/.../MainApplication.java

On top, where imports are:

import com.reactnativecommunity.netinfo.NetInfoPackage;

Add the NetInfoPackage class to your list of exported packages.

@Override
protected List<ReactPackage> getPackages() {
    return Arrays.asList(
            new MainReactPackage(),
            new NetInfoPackage()
    );
}
Manually link the library on Windows
  • Open the solution in Visual Studio for your Windows apps
  • Right click in the Explorer and click Add > Existing Project...
  • Navigate to ./<app-name>/node_modules/@react-native-community/netinfo/windows/RNCNetInfo/ and add RNCNetInfo.csproj
  • This time right click on your React Native Windows app under your solutions directory and click Add > Reference...
  • Check the RNCNetInfo you just added and press ok
  • Open up MainReactNativeHost.cs for your app and edit the file like so:
+ using ReactNativeCommunity.NetInfo;
......
        protected override List<IReactPackage> Packages => new List<IReactPackage>
        {
            new MainReactPackage(),
+           new RNCNetInfoPackage(),
        };

React Native Compatibility

To use this library you need to ensure you are using the correct version of React Native. If you are using a version of React Native that is lower than 0.57 you will need to upgrade that before attempting to use this library.

@react-native-community/netinfo versionRequired React Native Version
4.x.x>= 0.60 or >= 0.59 if using Jetifier
3.x.x>= 0.59
2.x.x>= 0.57
1.x.x>= 0.57

Migrating from the core react-native module

This module was created when the NetInfo was split out from the core of React Native. To migrate to this module you need to follow the installation instructions above and then change you imports from:

import { NetInfo } from "react-native";

to:

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

Note that the API was updated after it was extracted from NetInfo to support some new features, however, the previous API is still available and works with no updates to your code.

Usage

Import the library:

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

Get the network state once:

NetInfo.fetch().then(state => {
  console.log("Connection type", state.type);
  console.log("Is connected?", state.isConnected);
});

Subscribe to network state updates:

// Subscribe
const unsubscribe = NetInfo.addEventListener(state => {
  console.log("Connection type", state.type);
  console.log("Is connected?", state.isConnected);
});

// Unsubscribe
unsubscribe();

API

Types

NetInfoState

Describes the current state of the network. It is an object with these properties:

PropertyTypeDescription
typeNetInfoStateTypeThe type of the current connection.
isConnectedbooleanIf there is an active network connection. Note that this DOES NOT mean that internet is reachable.
isInternetReachablebooleanIf the internet is reachable with the currently active network connection.
detailsThe value depends on the type value. See below.

The details value depends on the type value.

type is none or unknown

details is null.

type is wifi

details has these properties:

PropertyPlatformTypeDescription
isConnectionExpensiveAndroid, iOS, WindowsbooleanIf the network connection is considered "expensive". This could be in either energy or monetary terms.
ssidAndroid, iOSstringThe SSID of the network. May not be present, null, or an empty string if it cannot be determined. On iOS, make sure your app meets at least one of the following requirements.
strengthAndroidnumberAn integer number from 0 to 5 for the signal strength. May not be present if the signal strength cannot be determined.
ipAddressAndroid, iOSstringThe external IP address. Can be in IPv4 or IPv6 format. May not be present if it cannot be determined.
subnetAndroid, iOSstringThe subnet mask in IPv4 format. May not be present if it cannot be determined.
type is cellular

details has these properties:

PropertyPlatformTypeDescription
isConnectionExpensiveAndroid, iOS, WindowsbooleanIf the network connection is considered "expensive". This could be in either energy or monetary terms.
cellularGenerationAndroid, iOS, WindowsNetInfoCellularGenerationThe generation of the cell network the user is connected to. This can give an indication of speed, but no guarantees.
carrierAndroid, iOSstringThe network carrier name. May not be present or may be empty if none can be determined.
type is bluetooth, ethernet, wimax, vpn, or other

details has these properties:

PropertyTypeDescription
isConnectionExpensivebooleanIf the network connection is considered "expensive". This could be in either energy or monetary terms.

NetInfoStateType

Describes the current type of network connection. It is an enum with these possible values:

ValuePlatformDescription
noneAndroid, iOS, WindowsNo network connection is active
unknownAndroid, iOS, WindowsThe network state could not or has yet to be be determined
cellularAndroid, iOS, WindowsActive network over cellular
wifiAndroid, iOS, WindowsActive network over Wifi
bluetoothAndroidActive network over Bluetooth
ethernetAndroid, WindowsActive network over wired ethernet
wimaxAndroidActive network over WiMax
vpnAndroidActive network over VPN
otherAndroid, iOS, WindowsActive network over another type of network

NetInfoCellularGeneration

Describes the current generation of the cellular connection. It is an enum with these possible values:

ValueDescription
nullEither we are not currently connected to a cellular network or type could not be determined
2gCurrently connected to a 2G cellular network. Includes CDMA, EDGE, GPRS, and IDEN type connections
3gCurrently connected to a 3G cellular network. Includes EHRPD, EVDO, HSPA, HSUPA, HSDPA, and UTMS type connections
4gCurrently connected to a 4G cellular network. Includes HSPAP and LTE type connections

Methods

fetch()

Returns a Promise that resolves to a NetInfoState object.

Example:

NetInfo.fetch().then(state => {
  console.log("Connection type", state.type);
  console.log("Is connected?", state.isConnected);
});

addEventListener()

Subscribe to connection information. The callback is called with a parameter of type NetInfoState whenever the connection state changes. Your listener will be called with the latest information soon after you subscribe and then with any subsequent changes afterwards. You should not assume that the listener is called in the same way across devices or platforms.

ParameterTypeDescription
listener(state:NetInfoState)=> voidThe listener which will be called whenever the connection state changes

Example:

// Subscribe
const unsubscribe = NetInfo.addEventListener(state => {
  console.log("Connection type", state.type);
  console.log("Is connected?", state.isConnected);
});

// Unsubscribe
unsubscribe();

useNetInfo()

A React Hook which can be used to get access to the latest state. It returns a hook with the NetInfoState type.

Example:

import {useNetInfo} from "@react-native-community/netinfo";

const YourComponent = () => {
  const netInfo = useNetInfo();

  return (
    <View>
      <Text>Type: {netInfo.type}</Text>
      <Text>Is Connected? {netInfo.isConnected.toString()}</Text>
    </View>
  );
};

Troubleshooting

Errors when building on Android

This library was migrated from using the support library to AndroidX in version 4.0.0. All of your depenencies must be using either the support library or AndroidX. Using a mixture of the two is not possible.

From React Native 0.60 AndroidX is used by default.

If you need to either convert this library back to the support library (to use an older React Native version) or convert other libraries forward to use AndroidX (if they have not been updated yet), you can use the Jetifier tool.

Errors while running Jest tests

If you do not have a Jest Setup file configured, you should add the following to your Jest settings and create the jest.setup.js file in project root:

setupFiles: ['<rootDir>/jest.setup.js']

You should then add the following to your Jest setup file to mock the NetInfo Native Module:

import { NativeModules } from 'react-native';

NativeModules.RNCNetInfo = {
  getCurrentState: jest.fn(() => Promise.resolve()),
  addListener: jest.fn(),
  removeListeners: jest.fn()
};

Issues with the iOS simulator

There is a known issue with the iOS Simulator which causes it to not receive network change notifications correctly when the host machine disconnects and then connects to Wifi. If you are having issues with iOS then please test on an actual device before reporting any bugs.

Maintainers

Contributing

Please see the contributing guide.

License

The library is released under the MIT license. For more information see LICENSE.