[React, Next.js] 모달(Modal) 생성 부 (모달 관련 파일 생성부분)
1. import ReactModal from "react-modal" 사용해 구현한 modal.tsx파일
http://reactcommunity.org/react-modal/
react-modal documentation
react-modal Accessible modal dialog component for React.JS We maintain that accessibility is a key component of any modern web application. As such, we have created this modal in such a way that it fulfills the accessibility requirements of the modern web.
reactcommunity.org
예제 코드
import React from 'react';
import ReactModal from "react-modal";
const customStyles = {
overlay: {
position: "fixed",
top: 0,
left: 0,
width: "100%",
height: "100%",
display: "flex",
alignItems: "center",
justifyContent: "center",
},
content: {
width: modalStyle?.width ? modalStyle?.width : "auto",
height: modalStyle?.height ? modalStyle?.height : "auto",
background: "white",
overflowY: "auto",
position: "relative",
inset: 0,
},
};
const ModalComponent: NextPage<any> = (props: any) => {
const modalState = useRecoilValue(atomModalState);
const modalOption = modalState.option ? modalState.option : "";
const modalStyle =
modalOption !== "" ? modalState.style : { width: "", height: "" };
useEffect(() => {
if (modalOption !== "") {
document.body.style.overflow = "hidden";
} else {
document.body.style.overflow = "unset";
}
}, [modalOption]);
return (
<ReactModal
isOpen={modalOption !== ""}
style={customStyles}
contentLabel="Example Modal"
>
{modalComponent(modalOption, props)}
</ReactModal>
);
};
export default ModalComponent;
- L41: <ReactModal></ReactModal>로 선언된 실질적으로 모달을 구현하는 ModalComponent 구성부
- L43: modalStyle에 따라 modalState에 지정된 modalStyle.style로 모달의 크기를 지정해준다.
- L42: modalOption이 ""일 때 모달이 꺼지는 동작을 수행해준다.
- L46: modalOption에 따라 modalMapping에서 원하는 모달로 열어준다.
2. 모달명마다 모달 Components를 매칭해주는 modalMapping.tsx파일
예제 코드
export const modalComponent = (option: ModalOption | string, props: any) => {
switch (option) {
case ModalOption.TEST:
return <TestComponent />;
case ModalOption.EXAMPLE:
return <ExampleComponent {...props} />;
default:
return null;
}
};
- ModalOption이 들어오면 해당하는 모달 컴포넌트를 호출해준다.
3. modalOption을 관리해주는 enum타입의 집한인 modalOption.ts파일
예제 코드
export enum ModalOption {
TEST = "test",
EXAMPLE = "example",
}
- ModalOption을 모아서 정리해주는 enum타입 데이터들의 집합
4. modalOption에 따른 모달 option과 style을 관리해주는 modalDictionary.ts파일
예제 코드
export const testModalSet = {
option: ModalOption.TEST,
style: { width: "400px", height: "200px" },
};
export const exampleModalSet = {
option: ModalOption.EXAMPLE,
style: { width: "640px", height: "360px" },
};
- ModalOption과 ModalStyle을 하나로 묶은 ModalState들의 집합
'개발 프레임워크 > Next.js' 카테고리의 다른 글
[Next.js] 개발환경 구축 및 Next.js 13으로 업데이트 (0) | 2023.03.04 |
---|---|
[React, Next.js] 모달(Modal) 구현_2 (recoil을 통한 제어) (0) | 2023.02.22 |
[Next.js] Warning: A component is Changing an uncontrolled input to be controlled Error (0) | 2023.02.09 |
useState로 배열, 객체의 값 변경(체크박스 구현) (0) | 2023.02.08 |
[Next.js] Slug (0) | 2023.02.03 |
댓글