React Native Netinfo Example

React Native Netinfo Example

Hello everyone, welcome to this new article, where we are going to explore the React Native Netinfo Api.
In this article we will try to make a simple Wifi Network Adapter, That gets the current network data in realtime.

Our final result will look like this.

React Native Netinfo Example

It’s pretty straightforward, and every time the strength of the Network changes, This icon will change.
By Strength, or to turn off, if the internet is not reachable.

Let’s Get Started

For a starter we can make a new project, either using Expo cli or React Native Cli.

For this example, I will be using an expo project, but if you prefer to use React Native Cli.
You can follow the instructions from Here.

Environment Setup

Install Netinfo from expo

expo install @react-native-community/netinfo

And import it

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

I will also be using Expo Icons, they come preinstalled with any Expo project, so no need to install them.
MaterialCommunityIcons in particular, Which has network icons for all network strength.

Then import it

import { MaterialCommunityIcons } from '@expo/vector-icons';

How does it React Native Netinfo work ?

Simply React Native Netinfo, allows us to get data related to the network we are connected to.

It provides extensive information that we can use from the name of the wifi, strength to Cellular Generation, carrier name and bluetooth etc

For this example we will only need to use the wifi related data, is it connected and the strength.
But you can use it to to get data from the table below.

cellularAndroid, iOS, Windows, WebActive network over cellular
wifiAndroid, iOS, Windows, WebActive network over Wifi
bluetoothAndroid, WebActive network over Bluetooth
ethernetAndroid, Windows, WebActive network over wired ethernet
wimaxAndroid, WebActive network over WiMax
vpnAndroidActive network over VPN

Get Wifi Data

To get the wifi network data, we can add an event listener, to netInfo, and subscribe to data changes in realtime.

NetInfo.addEventListener(state => {
  console.log('Connection type', state.type);
  console.log('Is connected?', state.isConnected);
});

Or, you can fetch data once

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

The state object thats being returned, contain the information we need.

typeNetInfoStateTypeThe type of the current connection. Examples in the table from previous section
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.
isWifiEnabledboolean(Android only) Whether the device’s WiFi is ON or OFF.
detailsThe value depends on the type value. See below.

And from the details section, if the network is wifi, we can get.

isConnectionExpensiveAndroid, iOS, Windows, WebbooleanIf the network connection is considered “expensive”. This could be in either energy or monetary terms.
ssidAndroid, iOS (not tvOS)stringThe SSID of the network. May not be present, null, or an empty string if it cannot be determined. 
strengthAndroidnumberAn integer number from 0 to 100 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.

Workflow

So, Let’s create state field to update data to.

I will add 3 fields

const [isInternetReachable, setIsInternetReachable] = useState(false)
const [strength, setStrength] = useState(0)
const [icon, setIcon] = useState("network-strength-off")

isInternetReachable: Wether the internet is being accessed or not

strength: The strength of the connection

icon: Icon for the UI

I will make a small helper function to get different Icons, based on the data we have in state.

  const getNetworkIcon=()=> {
    if(!strength){
      return "network-strength-off"
    }else if (strength <= 25) {
      return "network-strength-1"
    }else if (strength <= 50) {
      return "network-strength-2"
    }else if (strength <= 75) {
      return "network-strength-3"
    }else if (strength <= 100) {
      return "network-strength-4"
    } else if(!isInternetReachable){
      return "network-strength-outline"
    }
  }

Then, we will use the useEffect hook to setup the event listener for Netinfo.

In addition, the state update.

useEffect(() => {
    NetInfo.addEventListener(state => {
      setStrength(state.details.strength)
      setIsInternetReachable(state.isInternetReachable)
      setIcon(getNetworkIcon())
    });
  },[]);

With this hook, we are using componentDidUpdate, here you can find quick start on React Native Hooks guide.

And That was it, our app now will update based on network data in realtime.

React Native Netinfo
React Native Netinfo

Thank you for your time reading my article, I hope you find it as informative as you have expected.

Feel free to share it with your friends, and comment out your questions and concerns.

As usual I will add this project to github and expo.io for you to use.

Stay tuned for more.
Happy coding.

Total
26
Shares
2 comments
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
React Native Document & PDF Viewer

React Native Document & PDF Viewer

Next Post
React Native Box Shadow Example Featured

React Native Shadow Box Generator Example

Related Posts