Security News
NVD Backlog Tops 20,000 CVEs Awaiting Analysis as NIST Prepares System Updates
NVD’s backlog surpasses 20,000 CVEs as analysis slows and NIST announces new system updates to address ongoing delays.
@react-native-community/netinfo
Advanced tools
@react-native-community/netinfo is a React Native library that provides information about the device's network connection state. It allows developers to detect the type of network connection (WiFi, cellular, etc.), whether the device is connected to the internet, and other related details.
Check current network state
This feature allows you to fetch the current network state, including the connection type (e.g., WiFi, cellular) and whether the device is connected to the internet.
import NetInfo from '@react-native-community/netinfo';
NetInfo.fetch().then(state => {
console.log('Connection type', state.type);
console.log('Is connected?', state.isConnected);
});
Subscribe to network state changes
This feature allows you to subscribe to network state changes, so you can react to changes in the network connection in real-time.
import NetInfo from '@react-native-community/netinfo';
const unsubscribe = NetInfo.addEventListener(state => {
console.log('Connection type', state.type);
console.log('Is connected?', state.isConnected);
});
// Later, you can unsubscribe to stop listening for updates
unsubscribe();
Check if the device is connected to the internet
This feature allows you to check if the device is currently connected to the internet.
import NetInfo from '@react-native-community/netinfo';
NetInfo.fetch().then(state => {
console.log('Is connected?', state.isConnected);
});
Get detailed network information
This feature provides detailed information about the network connection, including whether the internet is reachable and additional details specific to the connection type.
import NetInfo from '@react-native-community/netinfo';
NetInfo.fetch().then(state => {
console.log('Connection type', state.type);
console.log('Is connected?', state.isConnected);
console.log('Is internet reachable?', state.isInternetReachable);
console.log('Details:', state.details);
});
react-native-network-info is another React Native library that provides information about the device's network state. It offers functionalities such as getting the SSID of the connected WiFi network and the IP address of the device. However, it does not provide as comprehensive a set of features for monitoring network state changes as @react-native-community/netinfo.
react-native-connection-info is a library that provides basic information about the network connection, such as the connection type and whether the device is connected to the internet. It is simpler and less feature-rich compared to @react-native-community/netinfo, making it suitable for applications that need only basic network information.
@react-native-community/netinfo
React Native Network Info API for Android, iOS, macOS & Windows. It allows you to get information on:
Install the library using either Yarn:
yarn add @react-native-community/netinfo
or npm:
npm install --save @react-native-community/netinfo
Linking the package manually is not required anymore with Autolinking.
iOS Platform:
$ npx pod-install
# 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
}
macOS Platform:
Autolinking is not yet available on macOS. See the Manual linking steps for macOS below.
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):
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'
Open your project .xcodeproj
on xcode.
Right click on the Libraries folder and select Add files to "yourProjectName"
.
Add RNCNetInfo.xcodeproj
(located at node_modules/@react-native-community/react-native-netinfo/macos
) to your project Libraries.
Go to Build Phases -> Link Binary with Libraries
and add: libRNCNetInfo-macOS.a
.
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()
);
}
./<app-name>/node_modules/@react-native-community/netinfo/windows/RNCNetInfoCPP/
and add RNCNetInfoCPP.vcxproj
RNCNetInfoCPP
you just added and press okpch.h
, add #include "winrt/ReactNativeNetInfo.h"
App.cpp
, add PackageProviders().Append(winrt::ReactNativeNetInfo::ReactPackageProvider());
before InitializeComponent();
./<app-name>/node_modules/@react-native-community/netinfo/windows/RNCNetInfo/
and add RNCNetInfo.csproj
RNCNetInfo
you just added and press okMainReactNativeHost.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(),
};
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 version | Required React Native Version |
---|---|
4.x.x & 5.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 |
The web implementation heavily depends on the Network Information API which is still an is an experimental technology and thus it's not supported in every browser. If this API is not available the library will safely fallback to the old onLine property and return basic connection information.
react-native
moduleThis 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.
Import the library:
import NetInfo from "@react-native-community/netinfo";
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();
Get the network state once:
NetInfo.fetch().then(state => {
console.log("Connection type", state.type);
console.log("Is connected?", state.isConnected);
});
NetInfoState
Describes the current state of the network. It is an object with these properties:
Property | Type | Description |
---|---|---|
type | NetInfoStateType | The type of the current connection. |
isConnected | boolean | If there is an active network connection. Note that this DOES NOT mean that internet is reachable. |
isInternetReachable | boolean | If the internet is reachable with the currently active network connection. |
isWifiEnabled | boolean | (Android only) Whether the device's WiFi is ON or OFF. |
details | The 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:
Property | Platform | Type | Description |
---|---|---|---|
isConnectionExpensive | Android, iOS, macOS, Windows, Web | boolean | If the network connection is considered "expensive". This could be in either energy or monetary terms. |
ssid | Android, iOS (not tvOS) | string | The 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. On Android, you need to have the ACCESS_FINE_LOCATION permission in your AndroidManifest.xml and accepted by the user. |
bssid | Android, iOS (not tvOS) | string | The BSSID 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. On Android, you need to have the ACCESS_FINE_LOCATION permission in your AndroidManifest.xml and accepted by the user. |
strength | Android | number | An integer number from 0 to 100 for the signal strength. May not be present if the signal strength cannot be determined. |
ipAddress | Android, iOS, macOS | string | The external IP address. Can be in IPv4 or IPv6 format. May not be present if it cannot be determined. |
subnet | Android, iOS, macOS | string | The subnet mask in IPv4 format. May not be present if it cannot be determined. |
frequency | Android | number | Network frequency. Example: For 2.4 GHz networks, the method will return 2457. May not be present if it cannot be determined. |
type
is cellular
details
has these properties:
Property | Platform | Type | Description |
---|---|---|---|
isConnectionExpensive | Android, iOS, macOS, Windows, Web | boolean | If the network connection is considered "expensive". This could be in either energy or monetary terms. |
cellularGeneration | Android, iOS, Windows | NetInfoCellularGeneration | The generation of the cell network the user is connected to. This can give an indication of speed, but no guarantees. |
carrier | Android, iOS | string | The 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:
Property | Type | Description |
---|---|---|
isConnectionExpensive | boolean | If 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:
Value | Platform | Description |
---|---|---|
none | Android, iOS, macOS, Windows, Web | No network connection is active |
unknown | Android, iOS, macOS, Windows, Web | The network state could not or has yet to be be determined |
cellular | Android, iOS, Windows, Web | Active network over cellular |
wifi | Android, iOS, macOS, Windows, Web | Active network over Wifi |
bluetooth | Android, Web | Active network over Bluetooth |
ethernet | Android, macOS, Windows, Web | Active network over wired ethernet |
wimax | Android, Web | Active network over WiMax |
vpn | Android | Active network over VPN |
other | Android, iOS, macOS, Windows, Web | Active network over another type of network |
NetInfoCellularGeneration
Describes the current generation of the cellular
connection. It is an enum with these possible values:
Value | Description |
---|---|
null | Either we are not currently connected to a cellular network or type could not be determined |
2g | Currently connected to a 2G cellular network. Includes CDMA, EDGE, GPRS, and IDEN type connections |
3g | Currently connected to a 3G cellular network. Includes EHRPD, EVDO, HSPA, HSUPA, HSDPA, and UTMS type connections |
4g | Currently connected to a 4G cellular network. Includes HSPAP and LTE type connections |
NetInfoConfiguration
The configuration options for the library.
Property | Type | Description |
---|---|---|
reachabilityUrl | string | The URL to call to test if the internet is reachable. Only used on platforms which do not supply internet reachability natively. |
reachabilityTest | (response: Response) => boolean | A function which is passed the Response from calling the reachability URL. It should return true if the response indicates that the internet is reachable. Only used on platforms which do not supply internet reachability natively. |
reachabilityShortTimeout | number | The number of milliseconds between internet reachability checks when the internet was not previously detected. Only used on platforms which do not supply internet reachability natively. |
reachabilityLongTimeout | number | The number of milliseconds between internet reachability checks when the internet was previously detected. Only used on platforms which do not supply internet reachability natively. |
reachabilityRequestTimeout | number | The number of milliseconds that a reachability check is allowed to take before failing. Only used on platforms which do not supply internet reachability natively. |
configure()
Configures the library with the given configuration. You only need to supply the properties which you want to change from the default values.
Note that calling this will stop all previously added listeners from being called again. It is best to call this right when your application is started to avoid issues.
Example:
NetInfo.configure({
reachabilityUrl: 'https://clients3.google.com/generate_204',
reachabilityTest: async (response) => response.status === 204,
reachabilityLongTimeout: 60 * 1000, // 60s
reachabilityShortTimeout: 5 * 1000, // 5s
reachabilityRequestTimeout: 15 * 1000, // 15s
});
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.
Parameter | Type | Description |
---|---|---|
listener | (state: NetInfoState ) => void | The 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>
);
};
You can optionally send configuration when setting up the hook. Note that configuration is global for the library, so you shouldn't send different configuration for different hooks. It is instead recommended that you called NetInfo.configure()
once when your project starts. The hook option is only provided as a convinience.
const YourComponent = () => {
const netInfo = useNetInfo({
reachabilityUrl: 'https://clients3.google.com/generate_204',
reachabilityTest: async (response) => response.status === 204,
reachabilityLongTimeout: 60 * 1000, // 60s
reachabilityShortTimeout: 5 * 1000, // 5s
reachabilityRequestTimeout: 15 * 1000, // 15s
});
// ...
};
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);
});
You can optionally send an interface
string so the Promise
resolves to a NetInfoState
from the NetInfoStateType
indicated in interface
argument.
NetInfo.fetch("wifi").then(state => {
console.log("SSID", state.details.ssid);
console.log("BSSID", state.details.bssid);
console.log("Is connected?", state.isConnected);
});
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.
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 mockRNCNetInfo from '@react-native-community/netinfo/jest/netinfo-mock.js';
jest.mock('@react-native-community/netinfo', () => mockRNCNetInfo);
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.
Please see the contributing guide.
The library is released under the MIT license. For more information see LICENSE
.
FAQs
React Native Network Info API for iOS & Android
The npm package @react-native-community/netinfo receives a total of 403,176 weekly downloads. As such, @react-native-community/netinfo popularity was classified as popular.
We found that @react-native-community/netinfo demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
NVD’s backlog surpasses 20,000 CVEs as analysis slows and NIST announces new system updates to address ongoing delays.
Security News
Research
A malicious npm package disguised as a WhatsApp client is exploiting authentication flows with a remote kill switch to exfiltrate data and destroy files.
Security News
PyPI now supports digital attestations, enhancing security and trust by allowing package maintainers to verify the authenticity of Python packages.