Skip to content

Instantly share code, notes, and snippets.

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