Home > Software design >  how to create dynamic ref names in a loop REACTjs
how to create dynamic ref names in a loop REACTjs

Time:08-03

I have 6 refs:

    const element0 = useRef(null)
    const element1 = useRef(null)
    const element2 = useRef(null)
    const element3 = useRef(null)
    const element4 = useRef(null)
    const element5 = useRef(null)

and i have a component which is being created in a loop: (component below is simplified)

             {documents.map((offer,i)=>(

                        <div ref={element...}> ////here is the problem. idk how to properly name ref in order to create references to all refs at the top.
                            <img src="......"/>
                        </div>
                    )
                )}

i tried to do it in many ways:

  <div ref={`element${i}`}>
  <div ref={element[i]}>

but it does not work ):

CodePudding user response:

you can store all elements in one ref, as you can see the below code.

const elementRef = useRef([]);

{documents.map((offer,i)=>(
        <div ref={ref => {
          elementRef.current[i] = ref
        }}>
        <img src="......"/>
     </div>
   )
)

}

CodePudding user response:

You need to use array of refs

const elementRefs = useRef([])

useEffect(() => {
   elementRefs.current = elementRefs.current.slice(0, documents.length);
}, [documents]);


{documents.map((offer,i)=>(

                    <div 
                       key={i} 
                       ref={el => elementRefs.current[i] = el} >
                        <img src="......"/>
                    </div>
                )
            )}

CodePudding user response:

You probably want to use the package use-dynamic-refs

npm i use-dynamic-refs

then you want to import useDynamicRefs into your code like that:

import useDynamicRefs from 'use-dynamic-refs';

and inside your functional component:

const [getRef, setRef] = useDynamicRefs();

at this point, you can simply do the following:

documents.map((offer,i)=>(
   // Use i or any other "id" that for you is easy to be retrieved later
   <div ref={setRef(i)}> 
      <img src="......"/>
   </div>
 )
)}

and at last, retrieve the refs by using getRef:

const myRef = getRef("my-index")

For more information, this is the npm page of the package used: https://www.npmjs.com/package/use-dynamic-refs

  • Related