Portals and Refs

Leveraging Separate Mount Points for Dynamic UI Elements

Setting up a separate mount point

  • Modify index.html and add another div to become a separate mount point for portal.

<!-- above #root -->
<div id="modal"></div>
  • Create a modal component.

  • Implement useRef to maintain a reference to the portals DOM element.

  • Utilize useEffect for cleanup.

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;

Implementing Modal

  • Import modal to Details.jsx

  • Utilize useState hook to control the visibility of the modal.

  • Show the modal when the button is clicked.

Last updated