Created
September 25, 2023 23:23
-
-
Save ixahmedxi/27c5e9cfd5fb00c8566d35ecb64da717 to your computer and use it in GitHub Desktop.
React resizable panel
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 { AnimatePresence, motion } from "framer-motion"; | |
import { PropsWithChildren } from "react"; | |
import useResizeObserver from "use-resize-observer"; | |
const ignoreCircularReferences = () => { | |
const seen = new WeakSet(); | |
return (key: string, value: Record<string, unknown>) => { | |
if (key.startsWith("_")) return; | |
if (typeof value === "object" && value !== null) { | |
if (seen.has(value)) return; | |
seen.add(value); | |
} | |
return value; | |
}; | |
}; | |
export function ResizablePanel({ children }: PropsWithChildren) { | |
const { ref, height } = useResizeObserver<HTMLDivElement>(); | |
return ( | |
<motion.div | |
animate={{ height: height || "auto" }} | |
className="relative w-full overflow-hidden" | |
> | |
<AnimatePresence initial={false}> | |
<motion.div | |
key={JSON.stringify(children, ignoreCircularReferences())} | |
initial={{ | |
opacity: 0, | |
}} | |
animate={{ | |
opacity: 1, | |
}} | |
exit={{ | |
opacity: 0, | |
}} | |
> | |
<div ref={ref} className={height ? "absolute" : "relative"}> | |
{children} | |
</div> | |
</motion.div> | |
</AnimatePresence> | |
</motion.div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment