react-keyed-flatten-children
Version:
Flattens React children and fragments to an array with predictable and stable keys
24 lines (23 loc) • 922 B
JavaScript
/* Returns React children into an array, flattening fragments. */
import { Children, isValidElement, cloneElement } from "react";
import { isFragment } from "react-is";
export default function flattenChildren(children, depth, keys) {
if (depth === void 0) { depth = 0; }
if (keys === void 0) { keys = []; }
return Children.toArray(children).reduce(function (acc, node, nodeIndex) {
if (isFragment(node)) {
acc.push.apply(acc, flattenChildren(node.props.children, depth + 1, keys.concat(node.key || nodeIndex)));
}
else {
if (isValidElement(node)) {
acc.push(cloneElement(node, {
key: keys.concat(String(node.key)).join('.')
}));
}
else if (typeof node === "string" || typeof node === "number") {
acc.push(node);
}
}
return acc;
}, []);
}