How to detect network connection in a JavaScript React app, and if offline, hide a component from user?

Sometimes, we want to detect network connection in a JavaScript React app, and if offline, hide a component from user.

In this article, we’ll look at how to detect network connection in a JavaScript React app, and if offline, hide a component from user.

How to detect network connection in a JavaScript React app, and if offline, hide a component from user?

To detect network connection in a JavaScript React app, and if offline, hide a component from user, we can listen to the online and offline events.

For instance, we write:

import React from "react";

export default function App() {
  const [online, setOnline] = React.useState(navigator.onLine);

  const onNetworkStatusChange = () => {
    setOnline(navigator.onLine);
  };

  React.useEffect(() => {
    window.addEventListener("online", onNetworkStatusChange);
    window.addEventListener("offline", onNetworkStatusChange);

    return () => {
      window.removeEventListener("online", onNetworkStatusChange);
      window.removeEventListener("offline", onNetworkStatusChange);
    };
  }, []);

  return <>{online ? <div>online</div> : <div>offline</div>}</>;
}

to call window.addEventListener with 'online' and 'offline' to listen for the online and offline events.

online event is emitted when the device is online and the offline event is emitted otherwise.

We set the event listener of each event to onNetworkStatusChange.

In it, we call setOnline with navigator.onLine to set the value of online.

navigator.onLine is true if the device is online and false otherwise.

We also call removeEventListener in the function we return in the useEffect callback to remove the listeners once the component is unmounted.

Then when the device is online we display ‘online’.

Otherwise, we display ‘offline’.

Conclusion

To detect network connection in a JavaScript React app, and if offline, hide a component from user, we can listen to the online and offline events.