Ever wondered how to detect an internet connection status of your app via React Native? Don't sweat it, it's why we've put together this tech tutorial, and the great news is, it's easy to implement.
If you're thinking, 'but why would I need to be able to track the internet connection?' then we've got news for you. It's super helpful for ensuring your app user doesn't lose any data if their internet dips out. By being able to track internet connection, you can launch a warning to the user or just block the screen so they won’t lose any data while the app tries to reconnect again. Don't worry, we'll show you exactly how to do this.
For this tutorial we're going to use a library called netInfo, which is maintained by the react-native-community (keep an eye on this resource, it'll come in very handy!). Here we can access all the goods. NetInfo used to be a native api in react native, but in the latest releases it has migrated to react-native-community.
To test our connection we will start a new project and in the App.js file, we'll show some info using this lib:
This is a simple example where we'll show a green or red square to indicate the internet connection status. Great, now for the fun part, it's time to install the required library.
Let's implement the command below in the root of your project:
npm install --save @react-native-community/netinfo
If you are using iOS also run:
And if you are using android, modify android/build.gradle configuration:
NetInfo can provide you with some more information about the connection that the smartphone is using. For example using signal.is, we can find out if the signal is from a cellular/mobile network (so 4g or 5g), if it's wifi, or bluetooth or even ethernet; if the phone is connected (this is the one we're focusing on), if the wifi is enabled and even the strength of the signal. Whilst these should be useful for you, you can brown the full list in the official docs.
To detect if the phone is connected we will use a hook provided by netInfo, useNetInfo. Let's declare a constant and use it as information about our status, see below:
We just need to import the hook, set a constant with it, and in the part where we set the colour of our background, we will use an attribute from useNetInfo, called isConnected. Seems pretty easy, right? And that's because it is!
To test it, we'd recommend trying it out on a physical device. You can use the emulator if you wish, but we think the real deal is the best choice. It should look something like this:
The final code is available here, netInfo is simple but powerful to control sensitive functions that will always require an internet connection to operate. Like what you've read or want more like this? Let us know! Email us here or DM us: Twitter, LinkedIn, Facebook, we'd love to hear from you.