react-modal 라이브러리로 Modal 만들기(typscript/recoil)

Wynter24·2023년 10월 13일
0

1. 설치

yarn add react-modal
yarn add @types/react-modal
yarn add @tailwindcss/forms

2. 'tailwind.config.js' 파일에서 해당 플러그인을 활성화

// tailwind.config.js
module.exports = {
  plugins: [
    require('@tailwindcss/forms'),
    // 다른 설정들...
  ],
};

3. Recoil로 modal 상태 전역으로 관리하기

import { atom } from 'recoil';

export const modalState = atom<boolean>({
  key: 'modalState',
  default: false,
});

4. 컴포넌트 파일

import React from 'react';
import ReactModal from 'react-modal';
import { useRecoilState } from 'recoil';
import { modalState } from '@/recoil/modalState';

const customModalStyles: ReactModal.Styles = {
  overlay: {
    backgroundColor: "rgba(0, 0, 0, 0.4)",
    width: "100%",
    height: "100vh",
    zIndex: 10,
    position: "fixed",
    top: 0,
    left: 0,
  },
  content: {
    width: "360px",
    height: "180px",
    zIndex: 150,
    position: "absolute",
    top: "50%",
    left: "50%",
    transform: "translate(-50%, -50%)",
    borderRadius: "10px",
    boxShadow: "2px 2px 2px rgba(0, 0, 0, 0.25)",
    backgroundColor: "white",
    justifyContent: "center",
    overflow: "auto",
  },
};


interface ModalProps {
  children: React.ReactNode;
  onRequestClose: () => void;
}

const Modal: React.FC<ModalProps> = ({ children, onRequestClose }) => {
  const [isOpen, setIsOpen] = useRecoilState(modalState);

  // 모달을 닫을 때 onRequestClose 함수 호출
  const closeModal = () => {
    onRequestClose();
  };

  return (
    <ReactModal
      isOpen={isOpen}
      style={customModalStyles} // 스타일 적용
      onRequestClose={closeModal} // 모달 창 닫기 요청을 받을 때 호출
      shouldCloseOnOverlayClick={true} // 외부 클릭으로 모달 닫기 활성화
    >
      <div className="modal-content">
        {children}
        <button onClick={closeModal}>닫기</button>
      </div>
    </ReactModal>
  );
};

export default Modal;
이름기능
isOpen모달 창이 표시되어야 하는지 여부를 설명하는 boolean 값이다. 즉, 해당 값이 true여야 모달 창이 열리는 것이다.
onRequestClose모달이 닫힐 때 실행될 함수를 의미한다. 즉,사용자가 모달을 닫으려고 할 때 실행되는 함수이다.
style모달 창과 모달 창 바깥에 대한 style을 지정해준다.
shouldCloseOnOverlayClick팝업창이 아닌 바깥 부분에서 클릭하였을 때, 닫히도록 할 것인지에 대한 처리이다. 기본값으로는 true를 가지고 있다.
shouldCloseOnOverlayClick외부를 클릭했을 때 모달이 닫히도록 설정할 수 있다.

5. 다른 파일에서 Modal 컴포넌트 사용

const Router = () => {
  const [isOpen, setIsOpen] = useRecoilState(modalState);
  const openModal = () => {
    setIsOpen(true);
  };

  const closeModal = () => {
    setIsOpen(false);
  };

  return (
    <BrowserRouter>
      <Routes>
        {/* ... */}
      </Routes>
      <button onClick={openModal}>모달 열기</button>
      <Modal onRequestClose={closeModal}>
        <h2>모달 제목</h2>
        <p>모달 내용을 여기에 추가합니다.</p>
      </Modal>
    </BrowserRouter>
  );
};

참고자료
React - 모달 창 구현해보기(라이브러리 react-modal)

profile
내가 다시 보려고 쓰는 개발.log

0개의 댓글