Detect network connection in React Redux app - if offline, hide component from user
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> ) }
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"const MyComponent = () => { return ( <div> <Offline>You're offline right now. Check your connection.</Offline> <Online>You're online right now.</Online> </div> );}
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