Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
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
Archives
Today
Total
관리 메뉴

new_bird-hyun

ReactDOM.createPortal로 모달 구현하기 본문

코딩 공부

ReactDOM.createPortal로 모달 구현하기

새혀니 2025. 4. 6. 20:01

// components/Modal.jsx
import ReactDOM from 'react-dom';

export default function Modal({ children, onClose }) {
  return ReactDOM.createPortal(
    <div className="overlay" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        {children}
      </div>
    </div>,
    document.getElementById('modal-root')
  );
}

 

<!-- public/index.html 또는 _document.tsx에 추가 -->
<div id="modal-root"></div>

 

 

// 사용 예
<Modal onClose={() => setOpen(false)}>
  <h2>모달 내용</h2>
</Modal>