
Online and offline events in ReactJS
A web apps that work both online and offline (or a slow network connection) has become relatively important in our life. Glad that browser provide related API for such event, online and offline events listener. How to do it in ReactJS using Hooks or HoC ?
#1 React Hooks
Below is a simple React Hooks for detect browser online and offline events.
import React, { useState, useEffect } from "react";
export default function useOnlineStatus() {
const [online, setOnline] = useState(true);
useEffect(() => {
window.addEventListener("online", handler);
window.addEventListener("offline", handler);
// cleanup
return () => {
window.removeEventListener("online", handler);
window.removeEventListener("offline", handler);
}
});
function handler(event) {
setOnline(navigator.OnLine);
if (event.type === "online") {
// handle stuffs when browser resume online
} else {
// handle stuffs when browser goes offline
}
}
return { online }
}
@ Example – Use it in UI Component
Prerequisite
import useOnlineStatus from "useOnlineStatus";
import SnackBar from "@material-ui/core/SnackBar";
function Demo() {
const status = useOnlineStatus();
return (
<>
<SnackBar
open={!status.online}
anchorOrigin={{ vertical: 'top', horizontal: 'center' }} />
<p>{status.online ? "Online" : "Offline" }</p>
</>
)
}
#2 Higher order Component
import React, { Component } from "react";
export default function withOnlineStatus(WrappedComponent) {
return class extends Component {
constructor() {
super();
this.state = {
online: true
}
}
componentDidMount() {
window.addEventListener("online", this.handler)
window.addEventListener("offline", this.handler)
}
componentWillUnmount() {
window.removeEventListener("online", this.handler)
window.removeEventListener("offline", this.handler)
}
handler = (event) => {
this.setState({ online: Navigator.OnLine })
if (event.type === "online") {
// handle stuffs when browser resume online
} else {
// handle stuffs when browser goes offline
}
}
render() {
const { online, ...rest } = this.props;
return <WrappedComponent online={online} {...rest} />
}
}
}
@ Example – Use it in UI Component
Prerequisite
- Material-UI – SnackBar
import SnackBar from "@material-ui/core/SnackBar";
import withOnlineStatus from "withOnlineStatus";
function Demo(props) {
const { online } = props;
return (
<>
<SnackBar
open={!online}
anchorOrigin={{ vertical: 'top', horizontal: 'center' }} />
<p>{online ? "Online" : "Offline" }</p>
</>
)
}
export default withOnlineStatus(Demo)
Thanks for reading. 😁
Comments
(0 Comments)