Skip to content

Instantly share code, notes, and snippets.

@SamSamskies
Created April 4, 2020 17:37
Show Gist options
  • Save SamSamskies/a5f9f8adfb248d4fe9c34ce2c7218397 to your computer and use it in GitHub Desktop.
Save SamSamskies/a5f9f8adfb248d4fe9c34ce2c7218397 to your computer and use it in GitHub Desktop.
Simple React Portal
import React, { useRef, useEffect } from 'react';
import { createPortal } from 'react-dom';
const Portal: React.FC = ({ children }) => {
const el = useRef<HTMLDivElement | null>(null);
useEffect(() => {
el.current = document.createElement('div');
document.body.appendChild(el.current);
return () => {
el.current!.remove();
};
}, []);
return el.current ? createPortal(children, el.current) : null;
};
export default Portal;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment