Skip to content

Instantly share code, notes, and snippets.

@gazdagergo
Last active December 12, 2018 06:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gazdagergo/7833156e096683b49a21133858d521ca to your computer and use it in GitHub Desktop.
Save gazdagergo/7833156e096683b49a21133858d521ca to your computer and use it in GitHub Desktop.
React children to flat array
import { Children } from 'react';
const getChildrenType = node => {
if (node === null) return 'null';
if (Array.isArray(node)) return 'array';
if (typeof node === 'object') return 'object';
return 'string';
}
const getElemType = elem => {
if (typeof elem === 'string') return 'string';
if (elem.props.children === undefined) return 'void';
return 'normal';
}
const reactChildrenToFlatArray = children => {
const result = Children.toArray(children).map(child => {
switch (getElemType(child)) { // Check node type
case 'void': // e.g. <br /> <img />
case 'string': // normal text
return child;
case 'normal': // any other html tag or component
switch (getChildrenType(child.props.children)) { // Check node content
case 'null': // e.g. <Elem>null</Elem>
case 'string': // e.g <Elem>foo</Elem>
case 'object': // e.g. <Elem><Foo /></Elem>
return child;
case 'array': // multiple children
reactChildrenToFlatArray(child.props.children);
break;
default: return child;
} break;
default: return child;
}
return child;
})
return result;
}
export default reactChildrenToFlatArray;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment