-
-
Save jrson83/5d67532c61a7b4c0fe839fab26f4fcaa to your computer and use it in GitHub Desktop.
Code-1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import * as React from 'react'; | |
| export const getNodeArray = <Props = any>( | |
| components: React.ReactNode, | |
| filter?: string | React.ComponentClass<any> | React.SFC<any>, | |
| ) => { | |
| let result = React.Children.toArray(components).map(React.Children.only) as React.ReactElement<Props>[]; | |
| if (filter) { | |
| result = result.filter((c) => { | |
| return c.type === filter; | |
| }); | |
| } | |
| return result; | |
| }; | |
| export const getChild = <P>( | |
| component: React.ReactElement<any>, | |
| filter: string | React.ComponentClass<any> | React.SFC<any>, | |
| ) => { | |
| const children = getNodeArray(component.props.children, filter); | |
| return children.shift() as React.ReactElement<P>; | |
| }; | |
| export const getAllChildFromArray = <ChildProps = any>( | |
| components: React.ReactElement<any>[], | |
| filter?: string | React.ComponentClass<any> | React.SFC<any>, | |
| ) => { | |
| const parents = getNodeArray<React.Props<any>>(components); | |
| const childrenResult: React.ReactElement<ChildProps>[] = []; | |
| parents.forEach((p) => { | |
| if (p.props.children) { | |
| const children = getNodeArray<ChildProps>(p.props.children, filter); | |
| childrenResult.push(...children); | |
| } | |
| }); | |
| return childrenResult; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment