2020-01-15 20:42:02 +05:00
|
|
|
import "./Modal.css";
|
|
|
|
|
|
|
|
import React, { useEffect, useState } from "react";
|
|
|
|
import { createPortal } from "react-dom";
|
2020-01-25 19:37:58 -03:00
|
|
|
import { KEYS } from "../keys";
|
2020-01-15 20:42:02 +05:00
|
|
|
|
|
|
|
export function Modal(props: {
|
|
|
|
children: React.ReactNode;
|
|
|
|
maxWidth?: number;
|
|
|
|
onCloseRequest(): void;
|
2020-01-25 19:37:58 -03:00
|
|
|
labelledBy: string;
|
2020-01-15 20:42:02 +05:00
|
|
|
}) {
|
|
|
|
const modalRoot = useBodyRoot();
|
2020-01-25 19:37:58 -03:00
|
|
|
|
2020-02-28 23:03:53 +01:00
|
|
|
const handleKeydown = (event: React.KeyboardEvent) => {
|
|
|
|
if (event.key === KEYS.ESCAPE) {
|
|
|
|
event.nativeEvent.stopImmediatePropagation();
|
2020-01-25 19:37:58 -03:00
|
|
|
props.onCloseRequest();
|
|
|
|
}
|
|
|
|
};
|
2020-01-15 20:42:02 +05:00
|
|
|
return createPortal(
|
2020-01-25 19:37:58 -03:00
|
|
|
<div
|
|
|
|
className="Modal"
|
|
|
|
role="dialog"
|
|
|
|
aria-modal="true"
|
|
|
|
onKeyDown={handleKeydown}
|
|
|
|
aria-labelledby={props.labelledBy}
|
|
|
|
>
|
2020-01-15 20:42:02 +05:00
|
|
|
<div className="Modal__background" onClick={props.onCloseRequest}></div>
|
|
|
|
<div className="Modal__content" style={{ maxWidth: props.maxWidth }}>
|
|
|
|
{props.children}
|
|
|
|
</div>
|
|
|
|
</div>,
|
2020-01-24 12:04:54 +02:00
|
|
|
modalRoot,
|
2020-01-15 20:42:02 +05:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
function useBodyRoot() {
|
|
|
|
function createDiv() {
|
|
|
|
const div = document.createElement("div");
|
|
|
|
document.body.appendChild(div);
|
|
|
|
return div;
|
|
|
|
}
|
|
|
|
const [div] = useState(createDiv);
|
|
|
|
useEffect(() => {
|
|
|
|
return () => {
|
|
|
|
document.body.removeChild(div);
|
|
|
|
};
|
|
|
|
}, [div]);
|
|
|
|
return div;
|
|
|
|
}
|