React Check Internet or Network Connection Status Tutorial

In this tutorial, we will teach how to gradually, and step-by-step detect the internet connection state Online / Offline in React js application using browser APIs.

In modern application, user-experience is the secret ingredient that intact the users’ interest. Providing internet connection status to the user is one of the best yet small feature.

Most React users want to know how to check whether the internet is connected or not. Not just that, but also how to check the internet is disconnected in React.

To check internet connectivity, we will use navigator.onLine, window.ononline, and window.onoffline.

The navigator.online returns the online status of the browser. It returns a boolean value, with true means online and false means offline. The property transmits updates whenever the browser’s capacity to connect to the network changes.

Apart from that, we will use window online and offline events to track the internet status in React. The offline event of the Window interface is invoked when the browser loses access to the network and the value of Navigator.onLine changes to false.

Create New React App

Let’s use the create react app tool to install a brand new React project.

npx create-react-app my-react-app

Head over to the app folder.

cd my-react-app

Add Bootstrap Library

This is completely optional, we are using this library to create the layout. However, you may use the custom CSS to design the component.

npm install bootstrap

Create Internet Status Component

You have to create the features/ folder inside the src/ directory.

Subsequently, make the new file, and name it features/InternetStatus.js and insert the following code to the file:

import React from 'react'

function InternetStatus() {
  return (
    <div></div>
  )
}

export default InternetStatus

Add No Internet Image

To show the no internet status, we are using a beautiful illustration from Freepik.com, make sure to create the src/assets folder and keep the illustration into the folder.

Detect Internet Status

When you open this app on the browser, you can turn on and off the internet, and you will see the network or internet connection state is dynamically changing.

In contrast, we also learned how to set a conditional initial value in the useState hook of the React functional component.

You have to get open the features/InternetStatus.js file, here you have to add the complete code.

import React, { useState, useEffect } from "react";
import noInternetImg from "../assets/no-internet.jpg";

function InternetStatus() {
  const [networkStatus, setNetworkStatus] = useState(() => {
    if (navigator.onLine) {
      console.log("Internet is connected.");
      return true;
    } else {
      return false;
    }
  });

  useEffect(() => {
    window.ononline = (e) => {
      console.log("Internet is connected.");
      setNetworkStatus(true);
    };

    window.onoffline = (e) => {
      console.log("The network connection has been lost.");
      setNetworkStatus(false);
    };
  }, [networkStatus]);

  return (
    <div>
      {networkStatus ? (
        <div className="alert alert-success">
          Internet connection is available
        </div>
      ) : (
        <img src={noInternetImg} alt="Logo" width={400} />
      )}
    </div>
  );
}

export default InternetStatus;

Update Global Component

We have created the component, now its time to register the component into the src/App.js file.

import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import InternetStatus from "./features/InternetStatus";

const App = () => {
  return (
    <div className="container mt-5">
      <h2 className="mb-4">React Check Internet Connection Status Example</h2>
      <InternetStatus />
    </div>
  );
};

export default App;

Run React Server

Move to the console and use command to run the react server.

npm start

You can use the below url to test the app.

http://localhost:3000

React Check Internet or Network Connection Status Tutorial

Image by storyset on Freepik

Conclusion

We used two browser APIs to find the network connection in React. One component shows the internet connection status another shows information about the internet connection is lost.