Skip to content
refs
33 lines · 1.3 KBRaw
1import { useLayoutEffect, useRef, type RefObject } from "react";
2
3const BOTTOM_GAP = 12;
4const MIN_HEIGHT = 448;
5
6/** Sizes an element to reach the bottom of the window from wherever it starts, so the map uses the whole page. */
7export function useFillHeight<T extends HTMLElement>(): RefObject<T | null> {
8 const ref = useRef<T>(null);
9 useLayoutEffect(() => {
10 const element = ref.current;
11 if (!element) return;
12 let frame = 0;
13 const fit = () => {
14 cancelAnimationFrame(frame);
15 frame = requestAnimationFrame(() => {
16 const top = element.getBoundingClientRect().top + window.scrollY;
17 const height = `${Math.max(MIN_HEIGHT, window.innerHeight - top - BOTTOM_GAP)}px`;
18 if (element.style.height !== height) element.style.height = height;
19 });
20 };
21 const first = element.getBoundingClientRect().top + window.scrollY;
22 element.style.height = `${Math.max(MIN_HEIGHT, window.innerHeight - first - BOTTOM_GAP)}px`;
23 window.addEventListener("resize", fit);
24 const above = new ResizeObserver(fit);
25 if (element.parentElement) above.observe(element.parentElement);
26 return () => {
27 cancelAnimationFrame(frame);
28 window.removeEventListener("resize", fit);
29 above.disconnect();
30 };
31 }, []);
32 return ref;
33}