Detect Network Connection In React Redux App - If Offline, Hide Component From User
Solution 1:
you can use the onLine method of the Navigator object, returns a boolean, true
if online, then just add a statement in your react render.
https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine
render(){
var input = navigator.onLine ? <YOUR_FORM_COMPONENT> : null;
return(
<div>
{input}
</div>
)
}
Solution 2:
I have been using react-detect-offline to handle displaying online/offline specific content, it handles older browsers who do not support the online event with polling and you can specify the polling URL in the options.
https://github.com/chrisbolin/react-detect-offline
First install the package
npm install react-detect-offline
Then in your component you would do something like
import { Offline, Online } from"react-detect-offline"constMyComponent = () => {
return (
<div><Offline>You're offline right now. Check your connection.</Offline><Online>You're online right now.</Online></div>
);
}
Solution 3:
navigator.onLine
will return the status whether it is online or offline but it wont check internet connectivity is there or not.
Adding bit more to @StackOverMySoul. To get rid of this can refer below example.
var condition = navigator.onLine ? 'online' : 'offline';
if (condition === 'online') {
console.log('ONLINE');
fetch('https://www.google.com/', { // Check for internet connectivitymode: 'no-cors',
})
.then(() => {
console.log('CONNECTED TO INTERNET');
}).catch(() => {
console.log('INTERNET CONNECTIVITY ISSUE');
} )
}else{
console.log('OFFLINE')
}
Why choose google.com?
The reason behind sending the get request to google.com instead of any random platform is because it has great uptime. The idea here is to always send the request to a service that is always online. If you have a server, you could create a dedicated route that can replace the google.com domain but you have to be sure that it has an amazing uptime.
Solution 4:
Use navigator.onLine
to check network connectivity. It return true if network connection is available else return false.
Also try to use navigator.connection to verify network connection status.
var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
if (connection) {
if (connection.effectiveType === 'slow-2g')
preloadVideo = false;
}
For more Network Information API
Post a Comment for "Detect Network Connection In React Redux App - If Offline, Hide Component From User"