How to ref to multiple components inside map

I need to set ref to each project inside map function. I'm forwardingRef from child to my parent and currently I'm getting only single Project. I need to set refs to array list and then work with it. I tried something like this:

    const projectSectionItem = useRef([])
    ref={projectSectionItem => projectSectionItem[index] = projectSectionItem}

PARENT:

  const projectSectionItem = useRef<HTMLDivElement>(null)

<StyledSection ref={projectSection}>
    {data.map((i, index) => {
        return i.showOnHP === 1 ?
            <Element name={index.toString()} key={index}>
                <Project
                    url={`${URL}${i.button_image.image}`}
                    client={i.client_name}
                    project={i.project.en}
                    btn_color={"#000"}
                    btn_text={i.button_text}
                    href={`/cases/${i.slug}`}
                    ref={projectSectionItem}
                >
                </Project>
            </Element>
            : null
    })}

CHILD:

export const Project = React.forwardRef<HTMLDivElement, ProjectProps>((props, ref) => {
    return (
        <StyledProject className={props.className} ref={ref}>
        ...
        </StyledProject>
    )

})

1 answer

  • answered 2020-06-02 10:12 Domino987

    Since you should not use hooks (useRef) in a loop or conditionally, you can just use createRef like this:

    const pressureRefs = data.filter(item => item.showOnHP).map(() => React.createRef<HTMLDivElement>())
    <Project ... ref={refs[i]} />