From 7e87696241380c094bbd3edc5214b8928bdf421d Mon Sep 17 00:00:00 2001 From: Yannick Monney Date: Tue, 3 Jan 2023 10:00:48 +0100 Subject: [PATCH 1/2] fix(modal): clear modal container ref on unmount --- src/lib/components/Modal/Modal.spec.tsx | 10 ++++++++++ src/lib/components/Modal/Modal.tsx | 17 ++++++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/lib/components/Modal/Modal.spec.tsx b/src/lib/components/Modal/Modal.spec.tsx index d2209c44e..7250b3059 100644 --- a/src/lib/components/Modal/Modal.spec.tsx +++ b/src/lib/components/Modal/Modal.spec.tsx @@ -24,6 +24,16 @@ describe('Components / Modal', () => { waitFor(() => expect(input).toHaveFocus()); }); + it('should be removed from DOM and garbage collected', async () => { + const root = document.createElement('div'); + + const { unmount } = render(); + + unmount(); + + await waitFor(() => expect(root.childNodes.length).toBe(0)); + }); + describe('A11y', () => { it('should have `role="dialog"`', async () => { const user = userEvent.setup(); diff --git a/src/lib/components/Modal/Modal.tsx b/src/lib/components/Modal/Modal.tsx index f3d57ae7d..63462b610 100644 --- a/src/lib/components/Modal/Modal.tsx +++ b/src/lib/components/Modal/Modal.tsx @@ -1,5 +1,5 @@ import classNames from 'classnames'; -import { ComponentProps, FC, PropsWithChildren, useRef } from 'react'; +import { ComponentProps, FC, PropsWithChildren, useEffect, useRef } from 'react'; import { createPortal } from 'react-dom'; import type { FlowbiteBoolean, FlowbitePositions, FlowbiteSizes } from '../Flowbite/FlowbiteTheme'; import { useTheme } from '../Flowbite/ThemeContext'; @@ -80,6 +80,21 @@ const ModalComponent: FC = ({ root.appendChild(containerRef.current); } + useEffect(() => { + return () => { + const container = containerRef.current; + + if (!container) { + return; + } + + // If a container exists on unmount, it is removed from the DOM and + // garbage collected. + container.parentNode?.removeChild(container); + containerRef.current = null; + }; + }, []); + return createPortal(
Date: Thu, 5 Jan 2023 09:27:54 +0100 Subject: [PATCH 2/2] Update Modal.tsx Only for codecov --- src/lib/components/Modal/Modal.tsx | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/lib/components/Modal/Modal.tsx b/src/lib/components/Modal/Modal.tsx index 63462b610..e4c50edf1 100644 --- a/src/lib/components/Modal/Modal.tsx +++ b/src/lib/components/Modal/Modal.tsx @@ -84,14 +84,12 @@ const ModalComponent: FC = ({ return () => { const container = containerRef.current; - if (!container) { - return; - } - // If a container exists on unmount, it is removed from the DOM and // garbage collected. - container.parentNode?.removeChild(container); - containerRef.current = null; + if (container) { + container.parentNode?.removeChild(container); + containerRef.current = null; + } }; }, []);