Skip to content

Instantly share code, notes, and snippets.

@jl-
Forked from jsdf/recursiveReactChildrenToArray.js
Created December 30, 2015 18:39
Show Gist options
  • Save jl-/b8b2eb4a34837669218f to your computer and use it in GitHub Desktop.
Save jl-/b8b2eb4a34837669218f 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