UNPKG

@ffsm/as-array

Version:

A lightweight React utility component that allows passing the same props to multiple children at once, simplifying component composition and reducing repetitive code.

55 lines (54 loc) 2.34 kB
var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime"; import { Children, cloneElement, Fragment, isValidElement, } from 'react'; /** * AsArray component that renders an array of children and passes the same props to each child. * * This component takes children elements and any additional props, then renders each child with * both its original props and the additional props passed to AsArray. * * Text nodes and non-valid React elements are rendered inside Fragment components. * Valid React elements are cloned with merged props. * * @param {PropsWithChildren<AsArrayProps>} props - Component properties * @param {React.ReactNode} props.children - Child elements to render * @param {Record<string, unknown>} props.rest - Additional props to pass to all child elements * @returns {JSX.Element} React Fragment containing the rendered children * * @example * // Pass className to all child buttons * <AsArray className="btn-primary"> * <button>Save</button> * <button>Cancel</button> * </AsArray> */ export function AsArray(props) { var children = props.children, rest = __rest(props, ["children"]); return (_jsx(_Fragment, { children: Children.toArray(children).map(function (child, index) { if (!isValidElement(child)) { return _jsx(Fragment, { children: child }, index); } return cloneElement(child, __assign(__assign({}, child.props), rest)); }) })); }