1
0

utils.ts 759 B

123456789101112131415161718192021222324
  1. import React, { ReactNode, isValidElement } from 'react';
  2. const REACT_FRAGMENT_TYPE = 'Symbol(react.fragment)';
  3. /**
  4. * Flatten the children and return the processed data
  5. */
  6. export const flatten = (children: ReactNode): Array<ReactNode> => {
  7. let res: Array<ReactNode> = [];
  8. React.Children.forEach(children, child => {
  9. if (child === undefined || child === null) {
  10. return;
  11. }
  12. if (Array.isArray(child)) {
  13. res = res.concat(flatten(child));
  14. } else if (isValidElement(child) && child.type && child.type.toString() === REACT_FRAGMENT_TYPE && child.props) {
  15. res = res.concat(flatten(child.props.children));
  16. } else {
  17. res.push(child);
  18. }
  19. });
  20. return res;
  21. };