@winglet/react-utils
Version:
React utility library providing custom hooks, higher-order components (HOCs), and utility functions to enhance React application development with improved reusability and functionality
27 lines (24 loc) • 1.17 kB
JavaScript
import { jsxs, jsx } from 'react/jsx-runtime';
import { useState, useRef, useMemo, Fragment } from 'react';
import { createPortal } from 'react-dom';
import { map } from '@winglet/common-utils/array';
import { getRandomString } from '@winglet/common-utils/lib';
import { PortalContext } from './PortalContext.mjs';
const PortalContextProvider = ({ children }) => {
const [components, setComponents] = useState([]);
const portalAnchorRef = useRef(null);
const value = useMemo(() => ({
portalAnchorRef,
register: (element) => {
const id = getRandomString(36);
setComponents((previous) => [...previous, { id, element }]);
return id;
},
unregister: (id) => {
setComponents((previous) => previous.filter((component) => component.id !== id));
},
}), []);
return (jsxs(PortalContext.Provider, { value: value, children: [children, portalAnchorRef.current &&
createPortal(jsx(Fragment, { children: map(components, ({ id, element }) => (jsx(Fragment, { children: element }, id))) }), portalAnchorRef.current)] }));
};
export { PortalContextProvider };