export function spreadFragmentInChildren()

in packages/rc-components/rc-actions/src/utils.tsx [88:118]


export function spreadFragmentInChildren(
  children: ReactNode,
  recursive = true
) {
  if (!isValidElement(children) && !Array.isArray(children)) {
    throw new Error(`expect a single react element of an array of element`)
  }
  const result: ReactNode[] = []
  // children can be a single element or array of it
  Children.forEach(children, (node) => {
    if (!isValidElement(node)) {
      // node maybe 0, '', boolean, null, undefined
      // React.Children.forEach auto spread array into nodes, so node can't be array
      result.push(node)
    } else if (
      node.type === React.Fragment &&
      node.props &&
      node.props.children
    ) {
      // node.props.children can be a single element or array of it
      if (recursive) {
        result.push(...spreadFragmentInChildren(node.props.children))
      } else if (Array.isArray(node.props.children)) {
        result.push(...node.props.children)
      } else result.push(node.props.children)
    } else {
      result.push(node)
    }
  })
  return result
}