Open this example in the interactive library
Live preview
Source code
// components/OnlineStatusMonitor.tsx
import { useState, useEffect } from "react";
export default function OnlineStatusMonitor({
label = "Workspace",
}: { label?: string } = {}) {
const [online, set] = useState<boolean | null>(null);
useEffect(() => {
const sync = () => set(navigator.onLine);
sync();
window.addEventListener("online", sync);
window.addEventListener("offline", sync);
return () => {
window.removeEventListener("online", sync);
window.removeEventListener("offline", sync);
};
}, []);
return (
<p role="status">
{label}: {online === null ? "Checking" : online ? "Online" : "Offline"}
</p>
);
}
