Created
September 17, 2020 20:18
-
-
Save nickdandakis/6c9074780d9bc15deecab33075e88454 to your computer and use it in GitHub Desktop.
A basic React Modal Portal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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