Skip to content

Instantly share code, notes, and snippets.

@fmartins-andre
Created August 20, 2023 23:09
Show Gist options
  • Save fmartins-andre/bb12ff7c53cf7c28a4e0ca86380fb77e to your computer and use it in GitHub Desktop.
Save fmartins-andre/bb12ff7c53cf7c28a4e0ca86380fb77e to your computer and use it in GitHub Desktop.
How to create unique refs for elements being rendered via array.map()

You could define a ref, and then inside the object, make multiple subvalues based on the key of the child:

const ref = useRef({})

{array.map((item)=><div key={item.id} ref={ref.current[item.id] ??= { current: null }}>{item.id}</div>)}

Example: https://playcode.io/1096173

Another approach is callback refs:

const ref = useRef({})
  {array.map((item)=><div key={item.id} ref={element => {
    if(element) {
      ref.current[item.id] = element
    } else {
      delete ref.current[item.id]
    }
  }}>{item.id}</div>)}

Example: https://playcode.io/1096186


Sources:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment