Last active
July 19, 2022 10:09
-
-
Save honungsburk/a8078189b62765bf3d69e87c96347c07 to your computer and use it in GitHub Desktop.
Whenever the "lead" DOM element is resized the function triggers and you can resize the follower DOM elements
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { RefObject, useEffect } from "react"; | |
/** | |
* | |
* @param resize the function that runs every time `lead` is resized | |
* @param leadRef the HTMLElement that we are tracking | |
*/ | |
export default function useOnResize<A extends HTMLElement>( | |
leadRef: RefObject<A>, | |
resize: (lead: A) => void, | |
deps: any[] | |
): void { | |
useEffect(() => { | |
const lead = leadRef.current; | |
if (lead) { | |
resize(lead); | |
const observer = new ResizeObserver(() => resize(lead)); | |
observer.observe(lead); | |
return () => observer.disconnect(); | |
} | |
}, [leadRef, ...deps]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment