Skip to content

Instantly share code, notes, and snippets.

@refo
Created March 20, 2017 11:45
Show Gist options
  • Save refo/551ccae42c7a1a8c858dccc703dc485a to your computer and use it in GitHub Desktop.
Save refo/551ccae42c7a1a8c858dccc703dc485a to your computer and use it in GitHub Desktop.
import React from 'react';
export default class ComponentName extends React.Component {
componentDidMount() {
let children = this.collectChildren(this, (child) => {
return 'object' === typeof child;
});
children = children.map(child => {
if (child.type && child.type.name) {
return child.type.name;
}
});
}
collectChildren = function () {
const noop = () => {
return true;
};
const collector = (obj, arr, test) => {
React.Children.map(obj.props.children, (child) => {
if (test(child)) {
arr.push(child);
}
if (child.props && child.props.children) {
collector(child, arr, test);
}
});
};
return (obj, test) => {
test = test || noop;
let arr = [];
collector(obj, arr, test);
return arr;
};
}();
render() {
return <div>
{this.props.children}
</div>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment