reactportaldom
React Portal - DOM 트리 밖으로 컴포넌트 렌더링하기
조회 0
React Portal은 컴포넌트를 부모 컴포넌트의 DOM 계층 구조 밖에 렌더링할 수 있게 해주는 기능입니다.
모달, 툴팁, 드롭다운 같은 UI 요소를 z-index 문제 없이 구현할 때 유용합니다.
1. Portal 기본 사용법
import { createPortal } from "react-dom";
function Modal({ children, isOpen }: { children: React.ReactNode; isOpen: boolean }) {
if (!isOpen) return null;
return createPortal(
<div className="modal-overlay">
<div className="modal-content">{children}</div>
</div>,
document.body
);
}
createPortal(children, container)형태로 사용container는 DOM 요소여야 합니다 (예:document.body,document.getElementById('modal-root'))
2. 이벤트 버블링과 Portal
Portal로 렌더링된 요소도 React 이벤트 시스템을 따릅니다.
function Parent() {
const handleClick = () => console.log("Parent clicked");
return (
<div onClick={handleClick}>
<>내용 {/* Portal로 body에 렌더링되지만, 이벤트는 부모로 버블링됨 */}
);
}