diff --git a/src/FocusRing.tsx b/src/FocusRing.tsx index d41939c..0054264 100644 --- a/src/FocusRing.tsx +++ b/src/FocusRing.tsx @@ -19,6 +19,12 @@ interface FocusRingComponentProps extends FocusRingProps { children: React.ReactElement; } +// ref: https://github.com/facebook/react/issues/14927 +const useLayoutEffect = + typeof window !== "undefined" && window.document && window.document.createElement + ? React.useLayoutEffect + : React.useEffect; + /** * Augments the child component to be able to render a focus ring */ @@ -66,7 +72,7 @@ export default function FocusRing(props: FocusRingComponentProps) { // Force the ring to update itself whenever this component re-renders // to stay up-to-date with the active element's properties. - React.useLayoutEffect(() => { + useLayoutEffect(() => { if (!enabled) return; ringContext.invalidate(); }); @@ -94,7 +100,7 @@ export default function FocusRing(props: FocusRingComponentProps) { // When using a remote focus ring (both `focusTarget` and `ringTarget` are // set), use native DOM event listeners to track when focus happens. - React.useLayoutEffect(() => { + useLayoutEffect(() => { if (focused != null) return; const target = focusTarget?.current; diff --git a/src/FocusRingContext.tsx b/src/FocusRingContext.tsx index dbda27f..fe0fb79 100644 --- a/src/FocusRingContext.tsx +++ b/src/FocusRingContext.tsx @@ -78,7 +78,7 @@ export class FocusRingContextManager { let current: Element | null = element; while (current != null) { elements.push(current); - styles.push(window.getComputedStyle(current)); + typeof window !== "undefined" && styles.push(window.getComputedStyle(current)); current = current.parentElement; } return { elements, styles }; @@ -168,7 +168,7 @@ export class FocusRingContextManager { } const GLOBAL_FOCUS_RING_CONTEXT = new FocusRingContextManager(); -GLOBAL_FOCUS_RING_CONTEXT.setContainer(document.body); +typeof window !== "undefined" && GLOBAL_FOCUS_RING_CONTEXT.setContainer(document.body); const FocusRingContext = React.createContext(GLOBAL_FOCUS_RING_CONTEXT);