[React] createPortal
createPortal
- 부모의 영향을 받지 않게 부모와 독립된 랜더링
<!-- public/index.html -->
<div id="root"></div>
<div id="modal"></div>
/* src/index.css */
#modal {
position: absolute;
top: 0;
left: 0;
}
// src/components/Modal.jsx
import ReactDOM from "react-dom";
const Modal = ({ children }) =>
ReactDOM.createProtal(children, document.querySelector("#modal"));
export default Modal;
// src/App.js
import "./App.css";
import React from "react";
function App() {
const [visible, setVisible] = useState(false);
const open = () => {
setVisible(true);
};
const close = () => {
setVisible(false);
};
return (
<div>
<button onClick={open}>open</button>
{visible && (
<Modal>
<div
style=
onClick={close}
>
Hello
</div>
</Modal>
)}
</div>
);
}
export default App;
댓글남기기