github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/ui/src/util/find.ts (about) 1 // Copyright 2018 The Cockroach Authors. 2 // 3 // Use of this software is governed by the Business Source License 4 // included in the file licenses/BSL.txt. 5 // 6 // As of the Change Date specified in that file, in accordance with 7 // the Business Source License, use of this software will be governed 8 // by the Apache License, Version 2.0, included in the file 9 // licenses/APL.txt. 10 11 import React from "react"; 12 13 /** 14 * findChildrenOfType performs a DFS of the supplied React children collection, 15 * returning all children which are ReactElements of the supplied type. 16 */ 17 export function findChildrenOfType<P>(children: React.ReactChild, type: string | React.ComponentClass<P> | React.SFC<P>): React.ReactElement<P>[] { 18 const matchingChildren: React.ReactElement<P>[] = []; 19 const childrenToSearch = React.Children.toArray(children); 20 while (childrenToSearch.length > 0) { 21 const child: React.ReactChild = childrenToSearch.shift(); 22 if (!isReactElement(child)) { 23 continue; 24 } else { 25 if (child.type === type) { 26 matchingChildren.push(child); 27 } 28 const { props } = child; 29 if (props.children) { 30 // Children added to front of search array for DFS. 31 childrenToSearch.unshift(...React.Children.toArray(props.children)); 32 } 33 } 34 } 35 36 return matchingChildren; 37 } 38 39 /** 40 * Predicate function to determine if a react child is a ReactElement. 41 */ 42 function isReactElement(child: React.ReactChild): child is React.ReactElement<any> { 43 return (<React.ReactElement<any>>child).type !== undefined; 44 }