Sarah
Sarah

Reputation: 171

Filter out children of a React component

I'm currently mapping the values of my parent components children in the following way:

const subRows = React.Children.map(this.props.children, (child, i) => {
  return child;
});

What I want is to target these children's type values so that I can filter out specific children in the return. Anyone know if there is an easy way to achieve this?

Upvotes: 14

Views: 15989

Answers (3)

nem035
nem035

Reputation: 35501

You access properties on a child via its props.

If you want to filter the children, you could use React.Children.toArray to obtain a normal JS array and then use its Array.prototype.filter method.

const subRows = React.Children.toArray(this.props.children).filter((child, i) => {
  return child.props.someProp;
});

Do keep in mind that:

React.Children.toArray() changes keys to preserve the semantics of nested arrays when flattening lists of children. That is, toArray prefixes each key in the returned array so that each element's key is scoped to the input array containing it.

You can also use React.Children.forEach and populate an array available in the outer scope:

const subRows = [];
React.Children.forEach(this.props.children, (child, i) => {
  if (child.props.someProp) {
    subRows.push(child)
  }
});

Upvotes: 18

fernandopasik
fernandopasik

Reputation: 10503

I've written a library to extend the React Children utilities, where there are functions for filtering and even deep filtering react components

https://fernandopasik.com/react-children-utilities/filter

import React from 'react';
import { filter } from 'react-children-utilities';

const Filtered = ({ children }) => (
  <div>
    {filter(children, (child) => child.type === 'span')}
  </div>
);


Upvotes: 2

Hemerson Carlin
Hemerson Carlin

Reputation: 7424

React.Children.toArray(this.props.children).filter(...)

Upvotes: 2

Related Questions