HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
💌
JJong’s Archive
/
⚽
공용 Component
/
Modal 컴포넌트

Modal 컴포넌트

태그
Feb 11, 2024
반투명 백그라운드와 모달 세트를 만들어보자!
  • 매개변수 : children, visible, onClose, div의 props(상속)
  • 리턴 : ReactPortal
 
  1. 백그라운드와 모달 div를 선언
  1. 백그라운드에 visible에 따라 style display를 none/block 처리
  1. 여태 만든 컴포넌트를 createPortal의 첫번째 인자로 넣음
    1. 두번째 인자는 document.body 바로 밑
    2. 혹은 새 div를 생성해 a에 append(useEffect안에)해서 이 안에
  1. useClickAway로 모달에 ref를 걸어주고 핸들러로 onClose를 전달해 모달이 아닌 곳을 누르면 닫히게 하기
  1. (모달 스타일) style props도 전달 받아 modal div의 스타일로 넣어준다
 
interface ModalProps extends HTMLAttributes<HTMLDivElement> { children: ReactNode; visible: boolean; onClose: () => void; } const Modal = ({ children, visible, onClose, ...props }: ModalProps) => { const ref = useClickAway(onClose); return createPortal( <div style={{ display: visible ? 'block' : 'none' }}> <div ref={ref} style={{ ...props.style }} > {children} </div> </div>, document.body, ); }; export default Modal;
 
<사용하기>
visible state를 사용
const [visible, setVisible] = useState(false); return ( <> <button onClick={() => setVisible(true)}>open modal</button> <Modal visible={visible} onClose={() => setVisible(false)} > hi </Modal> </> );