How to check internet connection(online or offline) in React

How to check internet connection(online or offline) in React

To check the internet connection in React application, you can use the navigator.onLine property which returns a Boolean indicating whether the browser is online or offline. You can add event listeners for the online and offline events and update the online status in the component's state.

Here's an example to learn how to check internet connection(online or offline) in React component:

  1. Create a new component or use an existing one where you want to track the internet connection status.

  2. Set up a state variable to store the online/offline status.

  3. Attach event listeners to the online and offline events of the window object to update the state accordingly.

  4. Clean up the event listeners when the component is unmounted.

Here's the code example:

import React, { useState, useEffect } from 'react';

const InternetConnectionStatus = () => {
  const [isOnline, setIsOnline] = useState(navigator.onLine);

  useEffect(() => {
    // Update the isOnline state when the connection status changes
    const handleOnline = () => {
      setIsOnline(true);
    };

    const handleOffline = () => {
      setIsOnline(false);
    };

    // Attach the event listeners
    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);

    // Clean up the event listeners
    return () => {
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
    };
  }, []); // Empty dependency array ensures the effect runs only once

  return (
    <div>
      Internet Connection Status: {isOnline ? 'Online' : 'Offline'}
    </div>
  );
};

export default InternetConnectionStatus;

In this example, the InternetConnectionStatus component initializes the state with the initial value of navigator.onLine using useState. Then, in the useEffect hook, event listeners are attached to the online and offline events, which update the state accordingly when the connection status changes. Finally, the event listeners are cleaned up when the component is unmounted.

You can use the InternetConnectionStatus component in your application wherever you need to display the internet connection status. The component will render "Online" or "Offline" based on the value of the isOnline state variable.

This approach works for most modern browsers, but keep in mind that the navigator.onLine property may not be reliable in all cases.

Using react-detect-offline package

The react-detect-offline package can help you to check the internet connection in React with a minimum line of code.

Here is an example of how you can implement this using the react-detect-offline package:

First, install the package using npm or yarn:

# For npm
npm install react-detect-offline

#For yarn
yarn add react-detect-offline

Next import the Offline and Online components from the package:

import { Offline, Online } from "react-detect-offline";

Use the Offline and Online components to render different elements based on the online status:

function InternetConnectionStatus () {
      return (
        <div>
              <Online>
                <p>You are online.</p>
              </Online>
              <Offline>
                <p>You are offline. Please check your internet connection.</p>
              </Offline>
        </div>
      );
}

In this example, we use the Online and Offline components to render different content based on the online status of the application. If the user is online, child components of <Online> will be rendered and when the user is offline, child components of <Offline> will be rendered.

The react-detect-offline package uses the navigator.onLine property internally to check the internet connection.But the main advantage of using this package is that it provides an easy-to-use API for rendering different content based on the online status of the application.

Conclusion

To check the internet connection(online or offline) in React, you can use the navigator.onLine property, which returns a boolean value indicating whether the browser is currently online or not. This approach involves using the useState and useEffect hooks to keep track of the online status and add event listeners for the online and offline events. As another option, you can use of a react-detect-offline package that simplifies the process of checking an internet connection in a React application. This package provides Online and Offline components that can be used to conditionally render content based on the user's device network connectivity.