Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | import React, { useState, useEffect, ReactPortal } from 'react';
import { createPortal, unmountComponentAtNode } from 'react-dom';
interface State {
render: (props: { children?: React.ReactNode }) => ReactPortal | null;
remove: (elm?: HTMLElement) => void;
}
export const usePortal = () => {
const [container] = React.useState<HTMLDivElement>(() => {
const el = document.createElement('div');
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) => {
elm && unmountComponentAtNode(elm);
};
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 };
};
|