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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | 6x 6x 21x 108x 108x | import { atom, useAtomValue, useSetAtom } from "jotai";
import { atomFamily } from "jotai/utils";
import { useCallback, useEffect } from "react";
import { createPortal } from "react-dom";
type PortalName = "aside" | "modal" | "notification";
type PortalMap = Partial<Record<PortalName, HTMLElement>>;
const portalsState = atom<PortalMap>({});
const portalElementState = atomFamily((portalName: PortalName) => {
return atom((get) => get(portalsState)[portalName]);
});
/**
* Returns a ref to be assigned to an element that will serve as a portal render target;
* the portal can be used by rendering inside a `<PortalEntrance name={name} />`
*/
function usePortalExit(name: PortalName) {
const setPortals = useSetAtom(portalsState);
const handlePortalRef = useCallback((node: HTMLElement | null) => {
setPortals((portals) => ({
...portals,
[name]: node,
}));
}, []);
useEffect(() => {
// cleanup function removes the reference to the portal exit element on unmount
return () => {
setPortals((portals) => ({
...portals,
[name]: undefined,
}));
};
}, []);
return handlePortalRef;
}
function PortalEntrance({
name,
children,
}: {
name: PortalName;
children?: React.ReactNode;
}) {
const portalElement = useAtomValue(portalElementState(name));
return (
<>{children && portalElement && createPortal(children, portalElement)}</>
);
}
export { PortalEntrance, usePortalExit };
|