DEV Community

Discussion on: 🚫😩 An array of react refs

Collapse
 
amantel profile image
Amantel

I tried just now, setting this.myRef = []; and using callbacks ref={(ref) => { this.myRef[someval] = ref; return true; }} - everything worked perfectly.

Collapse
 
elramus profile image
Luke Ramus

Thanks, this was helpful. If anyone else out there wants to do this with TypeScript and hooks, this worked like a charm for me:

const tentRefs = useRef<(HTMLDivElement | null)[]>([])

<div className="name-tent" key={studentId} ref={(ref) => { tentRefs.current.push(ref) }}>

Collapse
 
paddy57 profile image
Pradnyanand Milind Pohare

hello, how can i access stored values in myRef, like say what if i want to access next myRef value on currnet myRef, what should i do there? myRef.nextItem ?

Collapse
 
sunanda3055 profile image
sunanda3055

It worked for me as well. This is really cool. I have never used ref in loop and was facing issues, but with your help it rocked. Thanks!!