UNPKG

@kadoui/react

Version:

Kadoui primitive components for React

38 lines (37 loc) 1.32 kB
"use client"; import { jsx as _jsx } from "react/jsx-runtime"; import { usePathname } from "next/navigation"; import { useState, useEffect } from "react"; import { ModalContext } from "./ModalContext"; import { getBrowserScrollbarWith } from "../../utils"; export function ModalRoot({ children, defaultOpen = false }) { const pathname = usePathname(); const [isOpen, setOpen] = useState(defaultOpen); useEffect(() => { setOpen(false); }, [pathname]); useEffect(() => { const handleEscape = (e) => { if (e.key === "Escape") { setOpen(false); } }; document.addEventListener("keydown", handleEscape); return () => { document.removeEventListener("keydown", handleEscape); document.body.style.overflow = "unset"; }; }, []); useEffect(() => { const scrollbarWidth = getBrowserScrollbarWith(); if (isOpen) { document.body.style.overflow = "hidden"; document.body.style.paddingRight = `${scrollbarWidth}px`; } else { document.body.style.overflow = "unset"; document.body.style.paddingRight = "0px"; } }, [isOpen]); return _jsx(ModalContext, { value: { isOpen, setOpen }, children: children }); }