https://react-ko.dev/reference/react-dom/createPortal
<div>
<SomeComponent />
{createPortal(children, domNode, key?)}
</div>parameters
children: JSX or ๋ฌธ์์ด or ์ซ์ ๋ฑ ๋ฆฌ์กํธ๋ก ๋ ๋๋ง ํ ์ ์๋ ๋ชจ๋ ๊ฒdomNode:document.getElementById()๊ฐ ๋ฐํํ๋ ๊ฒ๊ณผ ๊ฐ์ ์ผ๋ถ DOM ๋ ธ๋key(optional) : ํฌํธ์ ํค๋ก ์ฌ์ฉํ ๊ณ ์ ๋ฌธ์์ด ๋๋ ์ซ์
Caveats
- ํฌํธ์ ์ด๋ฒคํธ๋ DOM ํธ๋ฆฌ๊ฐ ์๋ React ํธ๋ฆฌ์๋ฐ๋ผ ์ ํ๋๋ค
- ํฌํธ์ DOM ๋ ธ๋์ ๋ฌผ๋ฆฌ์ ๋ฐฐ์น๋ง ๋ณ๊ฒฝํ๋ค. ๋ค๋ฅธ ๋ชจ๋ ๋ฉด์์๋ JSX๋ ์ด๋ฅผ ๋ ๋๋งํ๋ React ์ปดํฌ๋ํธ์ ์์ ๋ ธ๋ ์ญํ ์ ํ๋ค.
Usage
Rendering React components into non-React server markup
๋ฆฌ์กํธ ๋ฃจํธ๊ฐ ๋ฆฌ์กํธ๋ก ๋น๋๋์ง ์์ ์ ์ ํ์ด์ง ๋๋ ์๋ฒ๋ ๋๋ง ํ์ด์ง์ ์ผ๋ถ์ผ ๋ ์ ์ฉํ ์ ์๋ค. ์ฌ๋ฌ๊ฐ ๊ฐ๋ณ React ๋ฃจํธ๋ฅผ ์ฌ์ฉํ๋ ๊ฒ๋ณด๋ค ํฌํธ์ ์ฌ์ฉํ์ฌ ์ฑ์ ์ผ๋ถ๊ฐ DOM์ ๋ค๋ฅธ ๋ถ๋ถ์ ๋ ๋๋ง ๋๋๋ผ๋ ์ฑ์ ๊ณต์ state๋ฅผ ๊ฐ์ง ๋จ์ผ React ํธ๋ฆฌ๋ก ์ฒ๋ฆฌํ ์ ์๋ค.
Rendering React components into non-React DOM nodes
ํฌํธ์ ์ฌ์ฉํด React ์ธ๋ถ์์ ๊ด๋ฆฌ๋๋ DOM ๋ ธ๋์ ์ฝํ ์ธ ๋ฅผ ๊ด๋ฆฌํ ์๋ ์๋ค
import { useRef, useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { createMapWidget, addPopupToMapWidget } from './map-widget.js';
export default function Map() {
const containerRef = useRef(null);
const mapRef = useRef(null);
const [popupContainer, setPopupContainer] = useState(null);
useEffect(() => {
if (mapRef.current === null) {
const map = createMapWidget(containerRef.current);
mapRef.current = map;
const popupDiv = addPopupToMapWidget(map);
setPopupContainer(popupDiv);
}
}, []);
return (
<div style={{ width: 250, height: 250 }} ref={containerRef}>
{popupContainer !== null && createPortal(
<p>Hello from React!</p>,
popupContainer
)}
</div>
);
}
import 'leaflet/dist/leaflet.css';
import * as L from 'leaflet';
export function createMapWidget(containerDomNode) {
const map = L.map(containerDomNode);
map.setView([0, 0], 0);
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: 'ยฉ OpenStreetMap'
}).addTo(map);
return map;
}
export function addPopupToMapWidget(map) {
const popupDiv = document.createElement('div');
L.popup()
.setLatLng([0, 0])
.setContent(popupDiv)
.openOn(map);
return popupDiv;
}
- ๋ฆฌ์กํธ ์ธ๋ถ์ ์๋ div์ ๋ด์ฉ์ ๋ฆฌ์กํธ๋ฅผ ์ฌ์ฉํ์ฌ ์ฑ์๋ฃ์ ์ ์์