React Native NetInfo Example to Detect Internet Connection Android iOS

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. So let’s get started .

What we are doing in this project: We are checking the internet connection status like device is connected to internet or not and according to that we would show a message on application screen with online and offline status text. This code runs in real time so if you minimize the app and reopen it then it will also detects internet connection in real time.

Contents in this project NetInfo Example to Detect Internet Connection in Live Mobile App in iOS Android Example Tutorial:

1. This step is very important for ANDROID applications, We need to put the ACCESS_NETWORK_STATE permission in AndroidManifest.xml file. So goto YourReactNativeProject -> android -> app -> src -> main -> AndroidManifest.xml and put below permission inside it. There is no configuration needed in iOS project.

2. Import StyleSheet, Text, View and NetInfo component in your project.

3. Create constructor() in your main export default class and inside the constructor() make a state named as connection_Status. This state is used to hold the connection status like Online and Offline.

4. Make a componentDidMount() inbuilt method in your class. Inside this method we would first implement the addEventListener() on the NetInfo and call the this._handleConnectivityChange function on connection change automatically. Now using the NetInfo.isConnected.fetch().done((isConnected)) we would detect the live internet connection status and if device is connected to live internet connection then set the state value.

5. Creating  componentWillUnmount() function in your class. Inside this function we would removing the listener from NetInfo using removeEventListener() method.

6. Creating the _handleConnectivityChange() function. We would calling this function each time when network connection status changed.

7. Creating a Text component inside render’s return block. In Text component we would show the connection status using State value.

8. Creating Style.

9. Complete source code for App.js File :

Screenshots in Android device:

React Native NetInfo Example to Detect Internet Connection

Screenshots in iOS device: