Blog>
Snippets

Fallback UI Components for Offline Mode

Design and implement a set of fallback UI components that are rendered when the app detects that it's operating in offline mode.
// Component to display when online
function OnlineComponent() {
  return (
    <div>
      <h1>You are online!</h1>
      {/* Regular app UI elements go here */}
    </div>
  );
}

// Component to display when offline
function OfflineComponent() {
  return (
    <div>
      <h1>You are offline!</h1>
      <p>Please check your connection. Some features may not be available.</p>
      {/* Fallback UI elements for offline mode go here */}
    </div>
  );
}

// Main app component that manages online/offline state
function App() {
  const [isOnline, setIsOnline] = React.useState(window.navigator.onLine);

  React.useEffect(() => {
    function updateOnlineStatus() {
      setIsOnline(window.navigator.onLine);
    }

    window.addEventListener('online', updateOnlineStatus);
    window.addEventListener('offline', updateOnlineStatus);

    return () => {
      window.removeEventListener('online', updateOnlineStatus);
      window.removeEventListener('offline', updateOnlineStatus);
    };
  }, []);

  return isOnline ? <OnlineComponent /> : <OfflineComponent />;
}
This code includes a simple React setup with two components: OnlineComponent and OfflineComponent. The App component manages the online/offline state using the browser's navigator.onLine property and window events to update the UI accordingly. React.useEffect is used to set up and clean up event listeners for 'online' and 'offline' events, which toggle the isOnline state. Depending on this state, the App component conditionally renders either the OnlineComponent or the OfflineComponent, effectively providing a fallback UI for when the app is offline.