clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

Set multiple React refs in one variable

Filed under: JavaScript— Tagged with: React

Storing multiple refs to an array or an object.

You can use an array or an object to store React refs, depending on if you have access to a name or an index.

Array ref

First setup the ref with useRef, initiate it with an empty array:

const refs = React.useRef([])

A click handler might look something like this:

const handleClick = index => {
  refs.current[index].focus()
}

Then set the ref like so:

<input
  ref={ref => !refs.current.includes(ref) && refs.current.push(ref)}
  placeholder={`Field ${index}`}
  type="text"
/>

Object ref

Pretty much the same, initiate with an empty object:

const refs = React.useRef({})

No push and no includes check:

<input
  ref={ref => (refs.current[name] = ref)}
  placeholder={`Field ${name}`}
  type="text"
/>

Demo

Multiple React refs demo

Comments would go here, but the commenting system isn’t ready yet, sorry.

  • © 2022 Antti Hiljá
  • About
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!