Skip to content

Commit

Permalink
refactor(usePortal): use createPortal directly (#368)
Browse files Browse the repository at this point in the history
  • Loading branch information
martesi authored Jul 4, 2024
1 parent 954666c commit 55d36cd
Showing 1 changed file with 10 additions and 43 deletions.
53 changes: 10 additions & 43 deletions packages/utils/src/usePortal.tsx
Original file line number Diff line number Diff line change
@@ -1,47 +1,14 @@
import React, { useState, useEffect, ReactPortal, useRef } from 'react';
import { PropsWithChildren, useCallback, useState } from 'react';
import { createPortal } from 'react-dom';
import { createRoot, Root } from 'react-dom/client';

interface State {
render: (props: { children: React.ReactNode }) => ReactPortal | null;
remove: (elm?: HTMLElement) => void;
}

export const usePortal = () => {
const ref = useRef<Root>();
const [container] = React.useState<HTMLDivElement>(() => {
const el = document.createElement('div');
ref.current = createRoot(el);
return el;
});
const [portal, setPortal] = useState<State>({
render: () => null,
remove: () => null,
});

const ReactCreatePortal = React.useCallback<(elmm: HTMLDivElement) => State>((elmm) => {
const Portal: State['render'] = ({ children }) => {
if (!children) return null;
return createPortal(children, elmm);
};
const remove: State['remove'] = (elm) => {
// https://stackoverflow.com/a/74445760/1334703
const timeout = setTimeout(() => {
elm && ref.current?.unmount();
clearTimeout(timeout);
});
};
return { render: Portal, remove };
}, []);

useEffect(() => {
if (container) portal.remove();
const newPortal = ReactCreatePortal(container);
setPortal(newPortal);
return () => {
newPortal.remove(container);
};
}, [container]);

return { Portal: portal.render, container };
const [container] = useState<HTMLDivElement>(() => document.createElement('div'));
const Portal = useCallback(
function Portal({ children }: PropsWithChildren) {
return createPortal(children, container);
},
[container],
);

return { Portal, container };
};

0 comments on commit 55d36cd

Please sign in to comment.