A no-frills React modal <dialog>
component. In addition to default
modal dialog behaviors, the component also disables body scrolling when the
modal is open.
Heavily inspired by https://web.dev/articles/building/a-dialog-component.
- Types
- Works with ESM and CJS
- Server-side rendering (SSR) compatible
- Click outside the modal to dismiss (default off)
- Prevent body scrolling when the modal is open (default on)
- BYOS: Bring your own styles 🧑🎤
{pnpm,npm,yarn} add @gsong/react-modal-dialog
import { useModal } from "@gsong/react-modal-dialog";
export default function Demo() {
const { Modal, openModal, closeModal } = useModal();
return (
<div style={{ height: "200vh" }}>
<button onClick={openModal}>Open Modal</button>
<Modal
allowBodyScroll
allowDismiss
onDismiss={() => console.debug("Dismissed")}
onCancel={() => console.debug("Canceled")}
onClose={() => console.debug("Closed")}
className="tailwind-stuff"
>
<div>Modal content</div>
<button onClick={closeModal}>Close Modal</button>
</Modal>
</div>
);
}
The useModal
hook returns an object with the following properties:
Modal
: The modal component.openModal
: A function to open the modal.closeModal
: A function to close the modal.
interface ModalProps extends React.DialogHTMLAttributes<HTMLDialogElement> {
allowBodyScroll?: boolean;
allowDismiss?: boolean;
onDismiss?: (event: React.MouseEvent<HTMLDialogElement, MouseEvent>) => void;
}
allowBodyScroll
: Allow the body to scroll when the modal is open. Defaults tofalse
.allowDismiss
: Allow the modal to be dismissed by clicking outside of it. Defaults tofalse
.onDismiss
: Called when the modal is dismissed.
openModal: () => void;
closeModal: () => void;
Breaking changes and what to do about them.
Instead of this:
openModal({ disableBodyScroll: false });
Do this:
<Modal allowBodyScroll />