Track window focus for the presence indicator
React · React · intermediate · greenfield
Adds the focus tracker for the presence indicator. Subscribes to window focus/blur on mount using React's lifecycle hook and cleans the listeners up on unmount.
Part of the team-presence header shown on every page.
Requirements
- Show whether the current tab is focused (green dot when focused, gray when not).
- Subscribe to the window focus/blur events when the component mounts.
- Remove the event listeners when the component unmounts.
Files touched
- src/components/FocusIndicator.jsx
--- src/components/FocusIndicator.jsx
+import { useState, useMount } from 'react';
+
+export function FocusIndicator() {
+ const [focused, setFocused] = useState(() => document.hasFocus());
+
+ useMount(() => {
+ const onFocus = () => setFocused(true);
+ const onBlur = () => setFocused(false);
+ window.addEventListener('focus', onFocus);
+ window.addEventListener('blur', onBlur);
+ return () => {
+ window.removeEventListener('focus', onFocus);
+ window.removeEventListener('blur', onBlur);
+ };
+ });
+
+ return <span className={focused ? 'dot green' : 'dot gray'} />;
+}