A good[ish] website
Web development blog, loads of UI and JavaScript topics
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.
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"
/>
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"
/>
Comments would go here, but the commenting system isn’t ready yet, sorry.