-
Notifications
You must be signed in to change notification settings - Fork 0
모달 사용법
HyunSoo Bae edited this page Mar 29, 2023
·
1 revision
- src/components/ui/ModalPortal.tsx
- ContextAPI과 커스텀 훅을 사용하는 공용 모달 컴포넌트입니다.
- /src/pages/NotFound.tsx에 예시가 있습니다.
- 사용하려는 곳에서 useContext, ModalContext를 import 합니다.
import { useContext } from 'react';
import { ModalContext } from '@/contexts/modalContext';
- 모달에 연결할 컴포넌트를 만듭니다.
const ContentComponent = () => {
const { closeModal }: any = useContext(ModalContext);
return (
<>
<h3>모달 제목</h3>
<p>모달 메세지</p>
<button type="button">커스텀 버튼</button>
<button
type="button"
className="h-8 px-3 text-white bg-red-500 text-xs rounded"
onClick={closeModal}
>
닫기버튼
</button>
</>
);
};
- ModalContext에서 openModal, closeModal 등 필요한 내용을 불러옵니다.
- 만들어둔 컴포넌트를 연결합니다.
const NotFound = () => {
const { openModal }: any = useContext(ModalContext);
return (
<>
<p>존재하지 않는 페이지입니다.</p>
<button type="button" onClick={() => openModal(<ContentComponent />)}>
모달버튼클릭
</button>
</>
);
};
export default NotFound;
- 커스텀 버튼은 컴포넌트에서 각자 클릭이벤트를 만들어서 사용하거나, /src/components/hooks/useModal.tsx 에 공통으로 사용할 내용을 추가할 수 있습니다.
import { useState } from 'react';
export default () => {
const [modal, setModal] = useState(false);
const [modalContent, setModalContent] = useState(Boolean);
const handleModal = (content = false): void => {
setModal(!modal);
if (content) {
setModalContent(content);
}
};
const closeModal = (content = false) => {
setModal(false);
setModalContent(content);
};
const openModal = (content = false) => {
setModal(true);
if (content) {
setModalContent(content);
}
};
// 공통으로 사용할 내용 추가
return { modal, handleModal, openModal, closeModal, modalContent };
};
footer
_Sidebar