Skip to content

Instantly share code, notes, and snippets.

@ajitid
Created September 15, 2021 21:58
Show Gist options
  • Save ajitid/bad29f27cbcdf28e5718eea21f4303b2 to your computer and use it in GitHub Desktop.
Save ajitid/bad29f27cbcdf28e5718eea21f4303b2 to your computer and use it in GitHub Desktop.
React portal
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