Created
November 22, 2018 14:07
-
-
Save pettaysergey/e22baa25572567290c2c097b450da10f to your computer and use it in GitHub Desktop.
Code-1
This file contains 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