How To Create Custom Modal/Dialog in React
Modals and Dialogs are ways you can focus users on a specific thing you want them to act upon. They are industry standard and super common in every application you visit. As a frontend engineer, knowing how to put one together is an essential skill and super easy to do.
Modal
A modal should be as flexible as possible. It should be possible to compose a modal of any type and size. Some with no footer header. Should be mindful of the vertical and horizontal view of real estate and more.
To start let's define the overall modal container.
import {ReactNode, SyntheticEvent} from "react";
import ‘./modal.scss’;
import {currentModal} from "./current-modal";
interface ModalProps {
id?: string;
children: ReactNode;
onClickOut: () => void;
}
export const Modal = ({children, onClickOut, id = "modal", ...otherProps}: ModalProps) => {
const handleOutsideClick = (e: SyntheticEvent<HTMLDivElement>) => {
if (typeof onClickOut === "function" && (e.target as Element).className === "modal-container") {
onClickOut();
}
}
return (
<div className="modal-container" onClick={handleOutsideClick}>
<dialog {...otherProps} id={id} className="modal">
{children}
</dialog>
</div>
)
}
- props: the modal takes 3 props. The
id
, a callback for click out, and the…