šŸš«šŸ˜© An array of react refs

Apparently you can't store React refs in an array. For some reason they get wiped out, so if you need to store a collection of refs, you have to do something like this (forgive me lord, for I hath sinned):

import React from 'react'

const collection = ["label 1", "label 2"]

class SinFactory extends React.Component {
  constructor(props) {
    super(props)
    this.ref0 = React.createRef()
    this.ref1 = React.createRef()
  }

  render() {
    return (
      <div>
        {collection.map((label, i) => {
          return <div key={label} 
            ref={this[`ref${i}`]}>{label}
          </div>
        })}
      </div>
    )
  }
}

It's truly filthy, but it works.


šŸš€šŸš€šŸš€ Thanks for reading my development journal, where I write about things I learn while building products.

The product I'm currently building is Follow Reset, which makes it easy to clean up your Twitter by helping you prune who you follow. Subscribe here to get notified when it launches, or head to the website to learn more. šŸ™šŸ™šŸ™

Show Comments