import type { ReactElement, FC } from "react"; import { Children, cloneElement } from "react"; import type { ILoop } from "./config/types"; import type { IComponentBaseProps } from "../../types/components"; /** * Компонент цикла. Используется для вывода нескольких одинаковых элементов * @returns {ReactElement} */ const Loop: FC = ({ length = 1, children = null, items = [] as ILoop["items"], }): ReactElement => { if (!children) { return <>; } const element = Children.only(children); const keyCounter = new Map(); const mock = new Array(length).fill(element); return ( <> {Children.map(mock, (child, index) => { const accessor = !!items ? items[index] : null; const customProps = (typeof accessor === "object" && !!accessor) ? accessor : {}; const keyBase = JSON.stringify({ childKey: child.key, accessor: customProps, }); const keyOrder = (keyCounter.get(keyBase) ?? 0) + 1; keyCounter.set(keyBase, keyOrder); return cloneElement(child, { ...child.props, key: `${keyBase}_${keyOrder}`, ...customProps, }); })} ); }; export type { ILoop }; export { Loop };