2
votes

I have react component A which renders a table. Data for one of the columns in the table is rendered through another component 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 component 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>
2
Can you describe what kind of action you want to perform on component B and if you are passing any property to them? In order to add Bs component, 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

2 Answers

4
votes
const 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 component to child components
 }));

  // to access you can use this.props.data or this.props.method in child component

you need to pass this {childrenProps} which include all child components.

3
votes

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
  }
}