groupByType()

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 | ReactNode[], types: (ComponentClass<any> | FunctionComponent | string)[], rest?: string): { [name: string]: ReactNode[] }

Arguments

children
The children array from the element where is used.
types
The types of elements that will be grouped. Different kind of types can be passed
  • Tag name string
  • React Element name string
  • React Element function
  • React Element class
rest
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.

Example

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

interface Props {
  children?: ReactNode;
}

const MyElement = (): ReactElement => <div />;

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

const Example = (): ReactElement => (
  <Grouped>
    <span>
      <b>1</b>
    </span>
    <MyElement />
    <span>
      <b>2</b>
    </span>
    <strong>3</strong>
  </Grouped>
);

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="my-element">
//     <MyElement />
//   </div>
//   <div className="empty"></div>
// </div>