chinds
chinds

Reputation: 1829

react get all children refs

I have a component that renders dynamic children, each of these children need to have a ref assigned to them e.g. ref={'childID' + index}

once the children have loaded I then need a way to loop over of the children and get their refs.

any way to do this?

Upvotes: 0

Views: 5461

Answers (2)

Yuya
Yuya

Reputation: 2311

You should be able to loop through this.refs object using Object.keys.

Object.keys(this.refs).forEach(key =>
  const ref = this.refs[key];
  ...
);

Upvotes: 2

Dan Prince
Dan Prince

Reputation: 30009

You can use the callback style for the ref prop to collect all the refs.

Here's a rough example of how this would look.

var refs = {};

function refCollector(id) {
  return function(element) {
    refs[id] = element;

    if(allRefsCollected()) {
      // do some work with all refs
    }
  }
}

function allRefsCollected() {
  return Object.keys(refs).length >= children.length;
}

return children.map((Child, index) => {
  return <Child ref={refCollector(index)} />;
});

When allRefsCollected returns true, you'll know that all the children have been rendered and refs will be an object, mapping id to element.

Upvotes: 1

Related Questions