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:

JavaScript
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:

JavaScript
# For npm
npm install react-detect-offline

#For yarn
yarn add react-detect-offline

Next import the Offline and Online components from the package:

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

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

JavaScript
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 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 react-detect-offline package that simplifies the process of checking 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.

Related Posts

React 19 New Features

React 19: New Features and Upcoming Major Releases in 2024

Get ready for some exciting news from the ReactJS official blog! If you love ReactJS, you’re in for a treat. We’ll take you through the latest cool stuff, like the supercharged React Compiler, the game-changing Actions, and new features in React Canary.

building ui elements with jsx

Building UI Elements with JSX and Components

Ready to dive into React? This chapter unlocks the secrets of JSX – writing HTML right in your JavaScript! We’ll also explore components, the reusable powerhouses of React .

Ultimate-Development-Environment-Setup-React.JS

Build React Apps Like a Boss: The Ultimate Development Environment Setup React.JS

Ready to transform static web pages into dynamic experiences? This guide unveils the secrets to setting up your React development environment, from essential tools to project structure. Discover Node.js, npm, and the perfect code editor for you. Equip your editor with powerful extensions for debugging, linting, and more. Learn how to organize your project like a pro and dive into the magic of reusable React components. Don’t wait! Build your foundation, unleash your creativity, and embark on your React journey today!

React 101 Featured

React 101: Your Beginner’s Guide to the Popular JavaScript Library

Dive into the world of React and unlock its potential for building dynamic, interactive web applications. This beginner-friendly guide covers everything you need to know, from core concepts to essential tools.

useeffect vs uselayouteffect

Mastering Your Side Effects: useEffect vs useLayoutEffect in React

React hooks have revolutionized the way we manage state and side effects in our components. But when it comes to side effects, two power players emerge: useEffect…

react-fiber

React Fiber: The Secret Sauce Behind Blazing-Fast React Apps

Discover the magic of React Fiber – the secret superhero enhancing React’s speed and intelligence. Analogous to an artist carefully drawing changes, Fiber’s behind-the-scenes tricks optimize rendering. Unlike the previous version, Fiber slices tasks, preventing app slowdowns during updates. This superhero ensures your app stays swift and responsive, making coding a seamless experience. Dive into the superhero world of React Fiber and level up your coding skills with the React docs. πŸš€

Leave a Reply

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