Skip to content

Instantly share code, notes, and snippets.

@nickdandakis
Created September 17, 2020 20:18
Show Gist options
  • Save nickdandakis/6c9074780d9bc15deecab33075e88454 to your computer and use it in GitHub Desktop.
Save nickdandakis/6c9074780d9bc15deecab33075e88454 to your computer and use it in GitHub Desktop.
A basic React Modal Portal
// Import dynamically without SSR, as this is expected to be rendered clientside only
// e.g. const ModalPortal = dynamic(() => import('~/shared/components/ModalPortal'), { ssr: false });
//
// Expects an empty div with id of `modal-portal-root` somewhere in the DOM
import React, { useRef, useEffect } from 'react';
import { createPortal } from 'react-dom';
function ModalPortal({ children }) {
const $modalPortalRoot = useRef();
const $el = useRef(document.createElement('div'));
useEffect(() => {
$modalPortalRoot.current = document.getElementById('modal-portal-root');
$modalPortalRoot.current.appendChild($el.current);
return () => $modalPortalRoot.current.removeChild($el.current);
}, []);
const modalElement = (
<div className="modal-portal">
{children}
</div>
);
return createPortal(
children && modalElement,
$el.current,
);
}
export default ModalPortal;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment