0

Got an interesting problem withs refs.

I'm mapping over a component and rendering it multiple times and passing a ref to each one

const ref = useRef()

{data.map(d) => (
  <Component
    {...lotsOfOtherProps}
    ref={ref}
  />
)}

Then in a grandchild component I have:

  const anotherRef = React.useRef()
  useImperativeHandle(ref, () => ({
    reset: () => {
      anotherRef?.current.reset()
    },
  }))

In this component I have a button and when I toggle it I call

anotherRef?.current?.reset() and this works and does what I want

but I'm wondering when I click a "reset all" button, how I can get all the refs to reset?

Red Baron
  • 7,181
  • 10
  • 39
  • 86
  • *"...and passing a ref to each one."* You're passing **the same** ref to each one. A ref can only hold **one** value, so you're just overwriting it each time. If you want a ref for every one of those, you'll need a ref for everyone of those, not just one. I haven't used `useImperativeHandle` so can't post a solution, but that's the problem. (I would probably try to find some other way to solve it, though, rather than [imperative code using refs](https://reactjs.org/docs/hooks-reference.html#useimperativehandle).) – T.J. Crowder Feb 24 '22 at 09:54

1 Answers1

0

You are replacing the ref with each iteration and finally assigning it to the last element. You need to create an array of refs.

const refs = [];

{
  data.map((d, index) => {
    const newRef = React.createRef();
    refs[index] = newRef;
    return <Component {...lotsOfOtherProps} ref={newRef} />;
  });
}

refs will contain the array of ref for each component created from data array.

Shan
  • 1,468
  • 2
  • 12