Currently, I am working on creating a Modal that should disable the scrollbar when opened. However, I am facing an issue where the scrollbar remains even after opening the Modal.
The Modal component is structured within a component and I am unable to pass the 'open' prop to the condition. This results in the scrollbar staying visible despite attempting to open the Modal.
In my Dialog.js file, I have defined an array and functions which are passed as props to other components like individual Modals.
Dialog.js
export default function Dialog() {
let [Dentistry, setDentistry] = useState(false);
let [Endodontics, setEndodontics] = useState(false);
let [Orthodontics, setOrthodontics] = useState(false);
const specializationsData = [
{
setOpen: setDentistry,
open: Dentistry,
},
{
setOpen: setEndodontics,
open: Endodontics,
},
{
id: 3,
setOpen: setOrthodontics,
open: Orthodontics,
},
];
return (
<>
<div className="grid gap-8 mx-auto md:grid-cols-3">
{specializationsData.map((item) => {
return (
<>
<Card setOpen={item.setOpen}>
<CardTitle>{item.title}</CardTitle>
<CardDescription>{item.text}</CardDescription>
</Card>
<Modal setOpen={item.setOpen} open={item.open}>
<ModalTitle>{item.title}</ModalTitle>
<ModalDescription>
{item}
</ModalDescription>
</Modal>
</>
);
})}
</div>
</>
);
}
Utilizing the Card component helps trigger the opening of the Modal successfully by passing the 'setOpen' prop from Dialog.js.
Card.js
export function Card({ setOpen, children }) {
return (
<>
<div
onClick={() => setOpen(true)}
className="px-4 py-6 text-center rounded-lg cursor-pointer select-none bg-gradient-to-br from-white to-neutral-50 drop-shadow-lg"
>
{children}
</div>
</>
);
}
On the contrary, there seems to be an issue with the 'open' prop not functioning correctly to hide the scrollbar when the Modal is open.
Modal.js
export function Modal({ open, setOpen, children }) {
if (typeof document !== "undefined") {
if (open) {
document.body.style.overflow = "hidden";
} else {
document.body.style.overflow = "";
}
}
return (
<>
<div
className={`${open ? "" : "hidden"} fixed z-10 inset-0 overflow-y-auto`}
>
<div className="flex items-center justify-center min-h-screen p-4">
<div className="fixed inset-0 bg-black opacity-30"></div>
<div className="relative w-full max-w-2xl p-8 mx-auto bg-white rounded-lg">
{children}
</div>
</div>
</div>
</>
);
}