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?
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)
}
});
React.Children.toArray(this.props.children).filter(...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With