This is the javascript function that allow you to check if the internet connection is available or not. Simply call this function will return true or false.
navigator.onLine
import React, { useState, useEffect } from 'react';
const Online = () => {
const [mode, setMode] = useState(navigator.onLine);
useEffect(() => {
window.addEventListener('online', handleNetwork);
window.addEventListener('offline', handleNetwork);
// componentDidMount()
// componentDidUpdate()
// componentWillUnMount()
return () => {
window.removeEventListener('online', handleNetwork);
window.removeEventListener('offline', handleNetwork);
}
}, [mode]); // value inside array will execute everytime after effect
const handleNetwork = (event) => {
setMode(!mode);
};
return (
<div>
<h1>Online status</h1>
<p> Mode: {mode ? "online" : "offline"} </p>
</div>
);
};
export default Online;
Useful Javascript function