I have react ponent A which renders a table. Data for one of the columns in the table is rendered through another ponent B, so <B/>
is child of <A/>
. I want to perform some action on <B/>
whenever user clicks anywhere on the page. This click event listener is defined inside A
. How can I loop through all <B/>s
from inside class A
? My ponent structure is something like this:
class A extends React.Component {
<B/>
<B/>
<B/>
<B/>
};
I came across React.Children.forEach
, but that is useful when children are passed as props via this.props.children
; i.e. when the code is something like this:
<A>some markup</A>
I have react ponent A which renders a table. Data for one of the columns in the table is rendered through another ponent B, so <B/>
is child of <A/>
. I want to perform some action on <B/>
whenever user clicks anywhere on the page. This click event listener is defined inside A
. How can I loop through all <B/>s
from inside class A
? My ponent structure is something like this:
class A extends React.Component {
<B/>
<B/>
<B/>
<B/>
};
I came across React.Children.forEach
, but that is useful when children are passed as props via this.props.children
; i.e. when the code is something like this:
<A>some markup</A>
Share
Improve this question
edited Nov 3, 2017 at 10:26
darKnight
asked Nov 3, 2017 at 9:38
darKnightdarKnight
6,48115 gold badges58 silver badges93 bronze badges
1
- Can you describe what kind of action you want to perform on ponent B and if you are passing any property to them? In order to add Bs ponent, how are you doing that? Maybe you have an array or another structure that holds the data and you are iterating through it or you are doing it just explicitly? – parecementeria Commented Nov 3, 2017 at 11:22
2 Answers
Reset to default 4const childrenProps = React.Children.map(this.props.children,
(child) => React.cloneElement(child, {
data : this.state,
method : this.method.bind(this)
// here you can pass state or method of parent ponent to child ponents
}));
// to access you can use this.props.data or this.props.method in child ponent
you need to pass this {childrenProps} which include all child ponents.
So I figured it out. I gave ref
to each <B/>
, and stored it in an array:
class A extends React.Component {
collectRefs = [];
<B ref={b => {this.collectRefs.push(b)}}/>
<B ref={b => {this.collectRefs.push(b)}}/>
<B ref={b => {this.collectRefs.push(b)}}/>
for(const b of collectRefs) {
// do stuff
}
}