From 266701a733549a0d2aa3c5a7bcf44466f65744e4 Mon Sep 17 00:00:00 2001 From: Nathan Vasse Date: Fri, 16 Feb 2024 17:18:32 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B(react)=20fix=20default=20opened=20?= =?UTF-8?q?modal?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .../react/src/components/Modal/index.spec.tsx | 16 ++++++++++++++++ packages/react/src/components/Modal/index.tsx | 17 +++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/packages/react/src/components/Modal/index.spec.tsx b/packages/react/src/components/Modal/index.spec.tsx index 5ddfd13..62e45f8 100644 --- a/packages/react/src/components/Modal/index.spec.tsx +++ b/packages/react/src/components/Modal/index.spec.tsx @@ -7,6 +7,22 @@ import { useModals } from ":/components/Modal/ModalProvider"; import { VariantType } from ":/utils/VariantUtils"; describe("", () => { + it("shows a modal opened by default", async () => { + const Wrapper = () => { + const modal = useModal({ isOpenDefault: true }); + return ( + + + +
Modal Content
+
+
+ ); + }; + render(); + expect(await screen.findByText("Modal Content")).toBeInTheDocument(); + }); + it("shows a modal when clicking on the button", async () => { const Wrapper = () => { const modal = useModal(); diff --git a/packages/react/src/components/Modal/index.tsx b/packages/react/src/components/Modal/index.tsx index 0b4bcb7..548567a 100644 --- a/packages/react/src/components/Modal/index.tsx +++ b/packages/react/src/components/Modal/index.tsx @@ -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 ; +}; + +export const ModalInner = (props: ModalProps) => { const ref = React.useRef(null); useEffect(() => {