Returns an object with keys that map each tag name to an array of children of that type, and a key that maps the rest of children.

groupByType(children: ReactNode, types: ReactNode[], rest?: string): { [name: string]: ReactNode[] }


The children array from the element where is used.
The types of elements that will be grouped.
The name of the group where the remaining elements will be grouped into.

Return Value

A new children array with the elements and their children that get produced by the callback function.


import React, { ReactElement, ReactNode } from 'react';
import { render } from 'react-dom';
import { groupByType } from 'react-children-utilities';

interface Props {
  children?: ReactNode;

const Grouped = ({ children }: Props): ReactElement => (
    <div className="spans">{groupByType(children, ['span', 'i'], 'rest').span}</div>
    <div className="rest">{groupByType(children, ['span', 'i'], 'rest').rest}</div>
    <div className="empty">{groupByType(children, ['span', 'i'], 'rest').i}</div>

const Example = (): ReactElement => (

render(<Example />, document.body);

// Result:
// <div>
//   <div className="spans">
//     <span>
//       <b>1</b>
//     </span>
//     <span>
//       <b>2</b>
//     </span>
//   </div>
//   <div className="rest">
//     <strong>3</strong>
//   </div>
//   <div className="empty"></div>
// </div>