0

I have a container (parent) Component that, among other things, renders a bunch of child components via a map. I need to create a ref in the Parent to the Child components. I now know you can not apply refs directly to Components. Refs need to be applied to DOM/HTML elements.

Assume a setup like:

ContainerComponent.js

export default function ContainerComponent() {
    const list = [1,2,3,4,5,6] // this could be an array of anything
    return (
        {list.map(item => <Child data={item} />)
    )
}

Child.js

export default function Child({data}) {
    // this could be more complex
    return (
        <p>{data}<p>
    )
}

Is there a way to create an of refs like:

const itemsRef = useRef(Array(list.length).fill(createRef()));

Then pass a reference to itemRef to Child via prop. Then set itemRef.current to the ref of the p element, many in a useEffect

Tithos
  • 1,191
  • 4
  • 17
  • 40
  • Does this help - https://stackoverflow.com/questions/54633690/how-can-i-use-multiple-refs-for-an-array-of-elements-with-hooks – Shyam Jun 02 '21 at 15:51
  • Thank you, but no. that example shoes the map function returning dom elements directly. In my example, the map function returns components – Tithos Jun 02 '21 at 15:57
  • 1
    Then you might need to use `forwardRef` . https://reactjs.org/docs/forwarding-refs.html – Shyam Jun 02 '21 at 16:00

0 Answers0