Mar 10, 2023 - 3 min read
React.createPortal is a method provided by React to render components outside the DOM hierarchy of their parent component. It allows you to mount a child node into a different part of the DOM, independent of where it is declared in your React component tree.
1import React, { useState } from "react";
2import ReactDOM from "react-dom";
3
4const App = () => {
5 const [showModal, setShowModal] = useState(false);
6
7 return (
8 <div>
9 <h1>React Portals Demo</h1>
10 <button onClick={()=> setShowModal(true)}>Open Modal</button>
11 {showModal && (
12 <Modal onClose={()=> setShowModal(false)}>
13 <h2>This is a modal</h2>
14 <button onClick={()=> setShowModal(false)}>Close</button>
15 </Modal>
16 )}
17 </div>
18 );
19};
20
21const Modal = ({ children, onClose }) => {
22 return ReactDOM.createPortal(
23 <div>
24 {children}
25 <button onClick={onClose}>Close Modal</button>
26 </div>,
27 document.getElementById("modal-root")
28 );
29};
30
31export default App;