Portals and Refs
Leveraging Separate Mount Points for Dynamic UI Elements
<!-- above #root -->
<div id="modal"></div>import React, { useEffect, useRef } from "react";
import { createPortal } from "react-dom";
const Modal = ({ children }) => {
// Implement useRef to maintain a reference to the portals DOM element.
const elRef = useRef(null);
if (!elRef.current) {
elRef.current = document.createElement("div");
}
// Utilize useEffect for cleanup.
useEffect(() => {
const modalRoot = document.getElementById("modal");
modalRoot.appendChild(elRef.current);
return () => modalRoot.removeChild(elRef.current);
}, []);
return createPortal(<div>{children}</div>, elRef.current);
};
export default Modal;
Last updated