React Native – NetInfo
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.
To Import NetInfo in Code
import NetInfo from '@react-native-community/netinfo'
To Get the Network State Once
NetInfo.getConnectionInfo().then((connectionInfo) => {
console.log(
'Initial, type: ' +
connectionInfo.type +
', effectiveType: ' +
connectionInfo.effectiveType);
});
Subscribe to Network State Updates
const unsubscribe = NetInfo.addEventListener(state => {
console.log(
'Connection type: ' +
state.type +
', Is connected?: ' +
state.isConnected);
});
To Unsubscribe the Network State Update
unsubscribe();
Run the following command to install
npm install @react-native-community/netinfo --save
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" />
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 NetInfo from '@react-native-community/netinfo'
import { AppState, Text } from 'react-native';
export default class App extends Component {
state = {
appState: AppState.currentState,
};
componentDidMount() {
NetInfo.fetch().then(state => {
console.log(
'Connection type: ' +
state.type +
', Is connected?: ' +
state.isConnected);
});
const unsubscribe = NetInfo.addEventListener(state => {
console.log(
'Connection type: ' +
state.type +
', Is connected?: ' +
state.isConnected);
});
}
render() {
return (
<Text style={{ marginTop: 30, padding: 20 }}>
NetInfo Example. Please open debugger to see the log
</Text>
);
}
}