Created
September 15, 2021 21:58
-
-
Save ajitid/bad29f27cbcdf28e5718eea21f4303b2 to your computer and use it in GitHub Desktop.
React 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 type { ReactNode } from 'react'; | |
import { useEffect, useRef } from 'react'; | |
import ReactDOM from 'react-dom'; | |
interface Props { | |
rootId: string; | |
children: ReactNode; | |
} | |
export const Portal = ({ rootId, children }: Immutable<Props>) => { | |
const elementRef = useRef(document.createElement('div')); | |
useEffect(() => { | |
const element = elementRef.current; | |
// eslint-disable-next-line unicorn/prefer-query-selector | |
const portalRoot = document.getElementById(rootId); | |
if (!portalRoot) { | |
throw new Error(`Element with id \`${rootId}\` does not exist in DOM.`); | |
} | |
portalRoot.append(element); | |
return () => { | |
element.remove(); | |
}; | |
}, [rootId]); | |
return ReactDOM.createPortal(children, elementRef.current); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment