index.tsx 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import React, { useEffect, useState } from 'react';
  2. import ReactDOM from 'react-dom';
  3. import { canUseDOM } from '../../helpers/dom';
  4. const createContainer = (zIndex: number): HTMLDivElement => {
  5. const container = document.createElement('div');
  6. container.setAttribute('class', 'portal');
  7. container.setAttribute('style', `z-index: ${zIndex};`);
  8. return container;
  9. };
  10. type Props = {
  11. zIndex?: number;
  12. children: React.ReactNode;
  13. };
  14. const Portal: React.FC<Props> = ({ zIndex = 0, children = '' }) => {
  15. const [container, setContainer] = useState(
  16. canUseDOM() ? createContainer(zIndex) : undefined,
  17. );
  18. useEffect(() => {
  19. if (container) {
  20. document.body.appendChild(container);
  21. } else {
  22. const newContainer = createContainer(zIndex);
  23. setContainer(newContainer);
  24. }
  25. return (): void => {
  26. if (container) {
  27. document.body.removeChild(container);
  28. }
  29. };
  30. }, []);
  31. return container ? ReactDOM.createPortal(children, container) : null;
  32. };
  33. export default Portal;