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'
/>