Skip to content

Instantly share code, notes, and snippets.

@khromov
Last active July 26, 2020 04:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khromov/87129e80231dc52d5b26297e32d5fca3 to your computer and use it in GitHub Desktop.
Save khromov/87129e80231dc52d5b26297e32d5fca3 to your computer and use it in GitHub Desktop.
React Progressive Web App Online / Offline warning message hook
import React, { useState, useEffect } from 'react';
function PWAOfflineStatus(props) {
const [isOnline, setOnlineStatus] = useState(true);
// https://stackoverflow.com/questions/44756154/progressive-web-app-how-to-detect-and-handle-when-connection-is-up-again
useEffect(() => {
const setFromEvent = function(event) {
if(event.type === 'online') {
setOnlineStatus(true);
}
else if(event.type === 'offline') {
setOnlineStatus(false);
}
}
window.addEventListener("online", setFromEvent);
window.addEventListener("offline", setFromEvent);
return() => {
window.removeEventListener("online", setFromEvent);
window.removeEventListener("offline", setFromEvent);
}
});
return !isOnline ? (
<>
<h5 className='pwa-warning'>
You are currently offline. <br/> Access to the application might be limited.
</h5>
<style jsx>{`
.pwa-warning {
background-color: orange;
color: black;
text-align: center;
padding: 10px;
}
`}</style>
</>) : null;
};
export default PWAOfflineStatus;

To use simply include this in your app via:

<PWAOfflineStatus />

Demo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment