Home > Net >  How can I use ref for the same component which is in the loop?
How can I use ref for the same component which is in the loop?

Time:04-23

array.map((el,i) =>{
      return(
          <Dropzone
          ref = {ref1}
          />
      )
    })

the question is it only ref to the last rendered Dropzone, how can I use ref through loop on all Dropzone component which is render in loop

CodePudding user response:

try:

  const refs = useRef([]);
  array.map((el,i) =>{
        refs.current[i] = createRef();
          return(
              <Dropzone
               ref={refs.current[i]}
              />
          )
        })

CodePudding user response:

For this, you have to use an array of refs which you can declare as const refs = useRef([]). After that, you can access individual elements as you access the elements of an array.

const Component = ({array}) => {
  
  const refs = useRef([])
  
  return (
    <>
      {array.map((el,i) => <Dropzone ref={el => (refs.current[i] = el)} /> )}
    </>
  )
  • Related