🐛(react) fix default opened modal

Modal with isOpen=true on first render were causing a crash. With
this approach we make sure the portal node is already rendered.

Fixes #259
This commit is contained in:
Nathan Vasse
2024-02-16 17:18:32 +01:00
committed by NathanVss
parent 95a6d6dec7
commit 266701a733
2 changed files with 33 additions and 0 deletions

View File

@@ -7,6 +7,22 @@ import { useModals } from ":/components/Modal/ModalProvider";
import { VariantType } from ":/utils/VariantUtils";
describe("<Modal/>", () => {
it("shows a modal opened by default", async () => {
const Wrapper = () => {
const modal = useModal({ isOpenDefault: true });
return (
<CunninghamProvider>
<button onClick={modal.open}>Open Modal</button>
<Modal size={ModalSize.SMALL} {...modal}>
<div>Modal Content</div>
</Modal>
</CunninghamProvider>
);
};
render(<Wrapper />);
expect(await screen.findByText("Modal Content")).toBeInTheDocument();
});
it("shows a modal when clicking on the button", async () => {
const Wrapper = () => {
const modal = useModal();

View File

@@ -52,6 +52,23 @@ export interface ModalProps
}> {}
export const Modal = (props: ModalProps) => {
/**
* This is a workaround to prevent the modal from rendering on the first render because if the modal is open on the
* first render, it will not be able to resolve document.getElementById("c__modals-portal") which is not rendered yet.
*/
const [firstRender, setFirstRender] = React.useState(true);
useEffect(() => {
setFirstRender(false);
}, []);
if (firstRender) {
return null;
}
return <ModalInner {...props} />;
};
export const ModalInner = (props: ModalProps) => {
const ref = React.useRef<HTMLDialogElement>(null);
useEffect(() => {