🚫😩 An array of react refs

ajsharp

Alex Sharp 🛠sharesecret.co

Posted on January 25, 2019

🚫😩 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>
    )
  }
}
Enter fullscreen mode Exit fullscreen mode

It's truly filthy, but it works.


☝️ Be sure to check out Sharesecret, which makes it easy to securely share sensitive data.

💖 💪 🙅 🚩
ajsharp
Alex Sharp 🛠sharesecret.co

Posted on January 25, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

🚫😩 An array of react refs
todayilearned 🚫😩 An array of react refs

January 25, 2019