0

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?

chinds
  • 1,761
  • 4
  • 28
  • 54
  • Why do you need their refs? – kpimov Feb 24 '16 at 12:40
  • Because I have a single component (a toggle switch) in the parent which renders the components with refs. I use the refs the call a function in the child component when the switch is toggled. I have it working now, but it only works on the last element rendered by the parent, so i think the issue is that multiple children can be rendered so they each need a unique ref. – chinds Feb 24 '16 at 13:14

2 Answers2

2

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

Object.keys(this.refs).forEach(key =>
  const ref = this.refs[key];
  ...
);
Yuya
  • 2,221
  • 1
  • 10
  • 16
0

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.

Dan Prince
  • 29,491
  • 13
  • 89
  • 120