Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import { useCallback, useEffect, useState } from "react";
import { DynamicModal, IDynamicModal } from "../lib/alerts";
import {
Button,
Modal,
ModalBody,
ModalContent,
ModalFooter,
ModalHeader,
} from "@nextui-org/react";
interface IModal {
id: number;
open: boolean;
modal: IDynamicModal;
}
/**
* React base to hold dynamic modals
*
* Dynamic modals are created via lib/alerts.tsx
*
* @returns
*/
export const DynamicModals = () => {
const [modals, setModals] = useState<IModal[]>([]);
const handleShowModal = useCallback(
(modal: IDynamicModal) => {
setModals((modals) => [
...modals,
{
id: Math.floor(Math.random() * 9999),
open: true,
modal,
},
]);
},
[setModals]
);
const handleHideModal = useCallback(
(modalId: number) => {
setModals((modals_) => {
const modals = [...modals_];
if (modals.find((m) => m.id === modalId)) {
modals.find((m) => m.id === modalId)!.open = false;
}
return modals;
});
setTimeout(() => {
setModals((modals_) => {
const modals = [...modals_];
if (modals.find((m) => m.id === modalId)) {
modals.splice(
modals.indexOf(modals.find((m) => m.id === modalId)!),
1
);
}
return modals;
});
}, 1000);
},
[setModals]
);
useEffect(() => {
DynamicModal.on("showModal", handleShowModal);
return () => {
DynamicModal.off("showModal", handleShowModal);
};
}, []);
return (
<>
{modals.map(({ id, open, modal }) => (
<Modal key={id} isOpen={open} onClose={() => handleHideModal(id)}>
<ModalContent>
{(onClose) => (
<>
<ModalHeader>{modal.title}</ModalHeader>
<ModalBody>{modal.body}</ModalBody>
<ModalFooter>
<Button onClick={onClose}>Close</Button>
</ModalFooter>
</>
)}
</ModalContent>
</Modal>
))}
</>
);
};