Skip to content

Instantly share code, notes, and snippets.

@jsdf
Created September 8, 2015 23:32
Show Gist options
  • Save jsdf/658bb65211eb2bce54d7 to your computer and use it in GitHub Desktop.
Save jsdf/658bb65211eb2bce54d7 to your computer and use it in GitHub Desktop.
Utility function to walk react element children and expand to an array of every element in tree (without removing children from elements)
import React from 'react';
export default function flattenReactChildrenToArray(nodeChildren, accumulated = []) {
React.Children.forEach(nodeChildren, (childNode) => {
accumulated.push(childNode);
if (childNode && childNode.props && childNode.props.children) {
flattenReactChildrenToArray(childNode.props.children, accumulated);
}
});
return accumulated;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment