Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(modal): clear modal container ref on unmount #514

Merged
merged 2 commits into from
Jan 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/lib/components/Modal/Modal.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(<TestModal root={root} />);

unmount();

await waitFor(() => expect(root.childNodes.length).toBe(0));
});

describe('A11y', () => {
it('should have `role="dialog"`', async () => {
const user = userEvent.setup();
Expand Down
15 changes: 14 additions & 1 deletion src/lib/components/Modal/Modal.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -80,6 +80,19 @@ const ModalComponent: FC<ModalProps> = ({
root.appendChild(containerRef.current);
}

useEffect(() => {
return () => {
const container = containerRef.current;

// If a container exists on unmount, it is removed from the DOM and
// garbage collected.
if (container) {
container.parentNode?.removeChild(container);
containerRef.current = null;
}
};
}, []);

return createPortal(
<ModalContext.Provider value={{ popup, onClose }}>
<div
Expand Down