waveterm/frontend/app/hook/useParentHeight.tsx
Red J Adaya d8ff2cb806
height adjuster (#94)
This hook observes and returns the current height of a component.
2024-07-04 09:07:06 -07:00

40 lines
1.1 KiB
TypeScript

// Copyright 2024, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0
import debounce from "lodash.debounce";
import { useCallback, useEffect, useState } from "react";
const useParentHeight = (ref: React.RefObject<HTMLElement>) => {
const [height, setHeight] = useState<number | null>(null);
const updateHeight = useCallback(() => {
if (ref.current) {
const parentHeight = ref.current.getBoundingClientRect().height || 0;
setHeight(parentHeight);
}
}, []);
const debouncedUpdateHeight = useCallback(debounce(updateHeight, 100), [updateHeight]);
useEffect(() => {
const resizeObserver = new ResizeObserver(() => {
debouncedUpdateHeight();
});
if (ref.current) {
resizeObserver.observe(ref.current);
updateHeight();
}
return () => {
if (ref.current) {
resizeObserver.unobserve(ref.current);
}
debouncedUpdateHeight.cancel();
};
}, [debouncedUpdateHeight, updateHeight]);
return height;
};
export { useParentHeight };