React 18 Function Component Detect Internet Network Status Tutorial

Last Updated on by in React JS

In this post, you will find out how to check the internet network connection Online status and, Offline status using React JS using window.ononline, window.onoffline APIs, React hooks in a functional component.

There are two ways through which we can build any functionality in React. The class component and the functional component.

We will display the network status using the function component with useState, and useEffect hooks.

The useState() is a commonly used Hook for state management in React. It permits you to encapsulate the local state in a functional component.

On the other hand, the useEffect Hook helps you handle side effects in React components.

The useState and useEffect hooks will help you check if the device is connected correctly to the internet in React.

Install React Application

The React CRA tool provides an intuitive way to manifest a new React project in your system without the need to create the new project manually.

Run command to download the new project.

npx create-react-app react-blog-app

Make sure you have entered it into the project folder.

cd react-blog-app

You are now ready to move to the subsequent step.

Build Function Component

A functional component is a traditional JavaScript method that offers to build features with pure JavaScript functions.

Now, make the components/ folder with Network.js file.

The Below code will create the function component.

import React from 'react'

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

export default Network

Setting Up Bootstrap

When creating any frontend app and that requires a basic knowledge of CSS. But no worries if your hand is a little tight in writing CSS.

The Bootstrap library offers the complete UI solution and offers tons of UI components.

npm i bootstrap --legacy-peer-deps

Register the bootstrap.min.css path in App.js file.

import "../node_modules/bootstrap/dist/css/bootstrap.min.css";

function App() {
  return <div></div>;
}

export default App;

Network Status Images

We will display the network status with relative illustrations.

Make the another folder within the src/ directory and, name it img/.

You have to keep the Connection Lost and Network Connected images within this directory.

Detect Network Status in React

Import the images from the img asset folder. The useState hook will update the network connection status when the network is alive or not.

Update code within the components/Network.js file.

import React, { useState, useEffect } from "react";
import connected from "../img/connected.jpg";
import networkLost from "../img/connection-lost.jpg";

function Network() {
  const [status, setStatus] = useState(() => {
    if (navigator.onLine) {
      console.log("Connected to network.");
      return true;
    } else {
      return false;
    }
  });

  useEffect(() => {
    window.ononline = (e) => {
      console.log("Connected to network.");
      setStatus(true);
    };

    window.onoffline = (e) => {
      console.log("Network connection lost.");
      setStatus(false);
    };
  }, [status]);

  return (
    <div>
      <h2 className="mb-3">React Detect Network Connection Status Example</h2>
      {status ? (
        <>
          <div className="alert alert-success mb-3">
            Network is fullly connected
          </div>
          <img src={connected} width={420} alt="Logo" />
        </>
      ) : (
        <img src={networkLost} width={420} alt="Logo" />
      )}
    </div>
  );
}

export default Network;

Update Global Component

The App() function is located in the App.js file. This simple method invokes on react app load and commemorates another component in one go. Hence, import and register the Network component here.

import Network from "./components/Network";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import "./App.css";

function App() {
  return (
    <div className="container">
      <Network />
    </div>
  );
}

export default App;

Start React Application

Here is the command for starting the React app; It will start the application server.

npm start
http://localhost:3000

React Function Component Detect Internet Network Status Tutorial

Conclusion

In this tutorial, we learned how to create the functionality that allows us to check the internet or network connection status in React.

This little step will benefit all the developers who are willing to know how to detect whether the internet is connected or the internet connection is lost or slow in React.