🐛(fix) fix body scroll when a modal is opened

It was possible to scroll the body when a modal is opened, it was
cutting the visibility of the modal, and was simply weird.

Fixes #263
This commit is contained in:
Nathan Vasse
2024-02-19 15:26:08 +01:00
committed by NathanVss
parent e9956829d1
commit 7f12f4d9b0
5 changed files with 254 additions and 1 deletions

View File

@@ -6,6 +6,7 @@ import React, {
PropsWithChildren,
ReactNode,
useContext,
useEffect,
useMemo,
useState,
} from "react";
@@ -25,6 +26,8 @@ import {
MessageModalProps,
} from ":/components/Modal/MessageModal";
export const NOSCROLL_CLASS = "c__noscroll";
export type Decision = string | null | undefined;
export type DecisionModalProps = WithOptional<ModalProps, "size"> & {
onDecide: (decision?: Decision) => void;
@@ -147,6 +150,28 @@ export const ModalProvider = ({ children }: PropsWithChildren) => {
[],
);
useEffect(() => {
const portalElement = document.getElementById("c__modals-portal")!;
// Create an observer instance linked to the callback function
const observer = new MutationObserver(() => {
const dialogs = portalElement.querySelectorAll("dialog");
if (dialogs.length > 0) {
document.querySelector("body")!.classList.add(NOSCROLL_CLASS);
} else {
document.querySelector("body")!.classList.remove(NOSCROLL_CLASS);
}
});
// Start observing the target node for configured mutations
observer.observe(portalElement, {
childList: true,
});
return () => {
observer.disconnect();
};
}, []);
return (
<ModalContext.Provider value={context}>
{children}