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