Last active
November 16, 2023 16:48
-
-
Save jide/4e8a0dfe1bdec2398e60fe37d08fbb34 to your computer and use it in GitHub Desktop.
Prevent grid layout overlap inside flex containers.
This file contains 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 { useState, useLayoutEffect, useCallback } from "react"; | |
import { flushSync } from "react-dom"; | |
const useDynamicMinHeight = (ref) => { | |
const [minHeight, setMinHeight] = useState(0); | |
const updateMinHeight = useCallback(() => { | |
if (ref.current) { | |
flushSync(() => { | |
setMinHeight(0); | |
}); | |
setMinHeight(ref.current.scrollHeight); | |
} | |
}, [ref]); | |
useLayoutEffect(() => { | |
// Update minHeight on mount and whenever the ref changes | |
updateMinHeight(); | |
// Handle window resize | |
window.addEventListener("resize", updateMinHeight); | |
// Cleanup | |
return () => { | |
window.removeEventListener("resize", updateMinHeight); | |
}; | |
}, [updateMinHeight]); | |
return minHeight; | |
}; | |
export default useDynamicMinHeight; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment