Back to all posts

React Portals


React, as a popular JavaScript library for building user interfaces, offers a powerful feature called “Portals.” These portals enable developers to render components outside the typical DOM hierarchy, allowing for greater flexibility and control over the structure of user interfaces.

Benefits of React Portals:

  • Separation of Concerns: Portals allow creating modular and reusable components without worrying about their positioning in the DOM.
  • Avoiding Style Conflicts: Rendering outside the parent component prevents unintended style conflicts or layout issues.
  • Improved User Experience: Portals facilitate creating overlays, modals, tooltips, and other UI components that seamlessly integrate into the user experience.

Index.html

 <div id="modal"></div>

Modal.jsx

import { createPortal } from "react-dom";
import { useEffect, useRef } from "react";

const Modal = ({ children, open, onClose, claasName = "" }) => {
  const dialog = useRef();

  useEffect(() => {
    const modal = dialog.current;
    if (open) {
      modal.showModal();
    }

    return () => modal.close();
  }, [open]);

  return createPortal(
    <dialog ref={dialog} className={`modal ${claasName}`} onClose={onClose}>
      {children}
    </dialog>,
    document.getElementById("modal"),
  );
};

export default Modal;

Example