Created the DialogContext.jsx

This commit is contained in:
Mathias Wagner 2023-06-02 20:15:11 +02:00
parent a3f940263f
commit 8109ff985c
Signed by: Mathias
GPG Key ID: B8DC354B0A1F5B44

View File

@ -0,0 +1,44 @@
import React, {createContext, useEffect, useRef} from "react";
import "./styles.sass";
export const DialogContext = createContext({});
export const DialogProvider = (props) => {
const areaRef = useRef();
const ref = useRef();
const close = (force = false) => {
if (props.disableClosing && !force) return;
areaRef.current?.classList.add("dialog-area-hidden");
ref.current?.classList.add("dialog-hidden");
}
const onClose = (e) => {
if (e.animationName === "fadeOut") {
props?.close();
}
}
const handleKeyDown = (e) => {
if (e.code === "Enter" && props.submit) props.submit();
}
useEffect(() => {
const handleClick = (event) => {
if (!ref.current?.contains(event.target)) close();
}
document.addEventListener("mousedown", handleClick);
}, [ref]);
return (
<DialogContext.Provider value={close}>
<div className="dialog-area" ref={areaRef}>
<div className={"dialog" + (props.customClass ? " " + props.customClass : "")} ref={ref}
onAnimationEnd={onClose} onKeyDown={handleKeyDown}>
{props.children}
</div>
</div>
</DialogContext.Provider>
)
}