Skip to content

Instantly share code, notes, and snippets.

@amitnovick
Created December 28, 2019 13:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save amitnovick/b87f61cadc0b63af88086cc0e0b2f37e to your computer and use it in GitHub Desktop.
Save amitnovick/b87f61cadc0b63af88086cc0e0b2f37e to your computer and use it in GitHub Desktop.
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>
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment