How to check how many Reata children have a certain support?

I have two types of components. Let me call them Outer and Inner. Imagine something like this:

<Outer> <h4>{this.prop.title} ({this.state.withX}/{this.state.total})</h4> <Inner isX/> <Inner isX/> <Inner/> <Inner/> </Outer> 

I have this function:

 getInitialState: function() { return { total: React.Children.count(this.props.children), withX: /// ??? /// }; } 

How do I get this value? I tried to get something like this:

 withX: function() { var counter = React.Children.forEach(this.props.children, function(child) { // if... return //something }); return counter; } 

But ... I feel that this will lead nowhere.

+6
source share
2 answers

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

+6
source

Now we have the React.Children.count(children) method described here https://facebook.imtqy.com/react/docs/react-api.html#react.children.count

UPDATE: after thinking, I’m not sure if this really answers the question, but it will leave here anyway, since people have already voted for it.

+6
source

All Articles