forked from grrowl/react-keyed-flatten-children
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
42 lines (41 loc) · 1000 Bytes
/
index.ts
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
/* Returns React children into an array, flattening fragments. */
import {
ReactNode,
ReactChild,
Children,
isValidElement,
cloneElement
} from "react";
import { isFragment } from "react-is";
export default function flattenChildren(
children: ReactNode,
depth: number = 0,
keys: (string | number)[] = []
): ReactChild[] {
return Children.toArray(children).reduce(
(acc: ReactChild[], 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;
},
[]
);
}