Skip to content

Instantly share code, notes, and snippets.

@luooooob
Forked from amitnovick/usePortal.js
Created September 1, 2021 01:59
Show Gist options
  • Save luooooob/cf5a7efa2824a9f729b899fb54901763 to your computer and use it in GitHub Desktop.
Save luooooob/cf5a7efa2824a9f729b899fb54901763 to your computer and use it in GitHub Desktop.

Revisions

  1. @amitnovick amitnovick created this gist Dec 28, 2019.
    43 changes: 43 additions & 0 deletions usePortal.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    import React from "react";
    import { createPortal } from "react-dom";

    function usePortal() {
    const portalElRef = React.useRef(document.createElement("div"));

    React.useEffect(() => {
    document.body.appendChild(portalElRef.current);

    return () => {
    if (portalElRef.current) {
    document.body.removeChild(portalElRef.current);
    }
    };
    }, [portalElRef]);

    const Portal = React.useCallback(
    ({ children }) => {
    if (portalElRef.current != null)
    return createPortal(children, portalElRef.current);
    return null;
    },
    [portalElRef]
    );

    return Portal;
    }

    export default usePortal;


    // Usage
    const ModalPortal = usePortal();

    return (
    <ModalPortal>
    <div className="overlay">
    <div className="content">
    <h2>This header is inside modal</h2>
    </div>
    </div>
    </ModalPortal>
    )