When you iterate over children, you can check their props. For example, using the forEach method that you specified above, you can do something like this:
withX: function() { var counter = 0; React.Children.forEach(this.props.children, function(child) { if (child.props.isX) counter++; }); return counter; }
React also provides a toArray helper that allows you to do the same using nice array methods. JS provides:
return React.Children.toArray(this.props.children).filter(function(child) { return child.props.isX; }).length;
If you are using ES6, you can do this fairly succinctly using the arrow function:
return React.Children.toArray(this.props.children).filter(c => c.props.isX).length;
The only catch is that if Outer does the counting, then Outer also needs to display h4 . Here is a complete example:
const App = React.createClass({ render() { return ( <Outer title="Things"> <Inner isX/> <Inner isX/> <Inner/> <Inner/> </Outer> ); } }); const Outer = React.createClass({ getInitialState() { return { total: React.Children.count(this.props.children), withX: this.countChildrenWithX(this.props.children) }; }, countChildrenWithX(children) { const { toArray } = React.Children; return toArray(children).filter(c => c.props.isX).length; }, render() { return ( <div> <h4>{this.props.title} ({this.state.withX}/{this.state.total})</h4> <hr /> {this.props.children} </div> ); } }); const Inner = React.createClass({ render() { return <div>Inner - withX = {String(!!this.props.isX)}</div>; } });
And here JS Bin works to demonstrate: https://jsbin.com/xameyun/edit?js,output
source share