forked from HireDiverSity-Dev/frontend_modules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseModal.tsx
82 lines (70 loc) · 1.98 KB
/
useModal.tsx
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
import { createContext, useContext, useEffect, useState } from 'react';
import { Modal } from '@mui/material';
import { Box, SxProps } from '@mui/system';
interface ModalProps {
children: React.ReactNode;
}
interface ModalContextType {
modal: React.ReactNode | null;
openModal: (RC: React.ReactNode, customSx?: SxProps, callBack?: () => void) => void;
closeModal: () => void;
}
const ModalContext = createContext<ModalContextType | undefined>(undefined);
const useModalImplement = () => {
const [modal, setModal] = useState<React.ReactNode | null>(null);
const [closeCallback, setCloseCallback] = useState<() => void | undefined>();
useEffect(() => {
//modal이 true에서 false로 바뀔때
if (!modal) {
if (closeCallback) closeCallback();
setCloseCallback(undefined);
}
}, [modal]);
const openModal = (RC: React.ReactNode, customSx?: SxProps, callBack?: () => void) => {
if (callBack) {
setCloseCallback(() => callBack);
}
setModal(
<Box
sx={{
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
bgcolor: 'background.paper',
boxShadow: 24,
p: 2,
borderRadius: 1,
maxWidth: '90%',
maxHeight: '90%',
...customSx,
}}
>
{RC}
</Box>,
);
};
const closeModal = () => {
setModal(null);
};
return { modal, openModal, closeModal };
};
const ModalProvider = ({ children }: ModalProps) => {
const modal = useModalImplement();
return (
<ModalContext.Provider value={modal}>
<Modal open={!!modal.modal} onClose={modal.closeModal}>
<>{modal.modal}</>
</Modal>
{children}
</ModalContext.Provider>
);
};
const useModal = () => {
const context = useContext(ModalContext);
if (!context) {
throw new Error('useModalContext must be used within a ModalProvider');
}
return context;
};
export { ModalProvider, useModal };