Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 886
Sarah Avatar asked Aug 24 '17 14:08

Sarah


Video Answer


2 Answers

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)
  }
});
like image 115
nem035 Avatar answered Sep 20 '22 11:09

nem035


React.Children.toArray(this.props.children).filter(...)
like image 22
mersocarlin Avatar answered Sep 23 '22 11:09

mersocarlin