snort/src/Element/Modal.tsx

44 lines
1.1 KiB
TypeScript
Raw Normal View History

2022-12-30 23:35:02 +00:00
import "./Modal.css";
2023-01-28 22:07:37 +00:00
import { useEffect, useRef } from "react"
2023-01-16 17:48:25 +00:00
import * as React from "react";
2022-12-30 23:35:02 +00:00
2023-01-16 17:48:25 +00:00
export interface ModalProps {
2023-01-28 21:52:05 +00:00
className?: string
2023-01-16 17:48:25 +00:00
onClose?: () => void,
children: React.ReactNode
}
2023-01-28 22:07:37 +00:00
function useOnClickOutside(ref: any, onClickOutside: () => void) {
useEffect(() => {
function handleClickOutside(ev: any) {
if (ref && ref.current && !ref.current.contains(ev.target)) {
onClickOutside()
}
}
document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, [ref]);
}
2023-01-16 17:48:25 +00:00
export default function Modal(props: ModalProps) {
2023-01-28 22:07:37 +00:00
const ref = useRef(null);
2023-01-12 09:57:35 +00:00
const onClose = props.onClose || (() => { });
2023-01-28 21:52:05 +00:00
const className = props.className || ''
2023-01-28 22:07:37 +00:00
useOnClickOutside(ref, onClose)
2022-12-30 23:35:02 +00:00
useEffect(() => {
document.body.classList.add("scroll-lock");
return () => document.body.classList.remove("scroll-lock");
}, []);
return (
2023-01-28 22:07:37 +00:00
<div className={`modal ${className}`}>
<div ref={ref} className="modal-body">
2022-12-30 23:35:02 +00:00
{props.children}
2023-01-25 18:08:53 +00:00
</div>
2022-12-30 23:35:02 +00:00
</div>
)
2023-01-25 18:08:53 +00:00
}