I looking for a solution about get an array of DOM elements with react useRef()
hook.
example:
const Component = () =>
{
// In `
I'll expand on skyboyer's answer a bit. For performance optimization (and to avoid potential weird bugs), you might prefer to use useMemo
instead of useRef
. Because useMemo accepts a callback as an argument instead of a value, React.createRef
will only be initialized once, after the first render. Inside the callback you can return an array of createRef
values and use the array appropriately.
Initialization:
const refs= useMemo(
() => Array.from({ length: 3 }).map(() => createRef()),
[]
);
Empty array here (as a second argument) tells React to only initialize refs once. If ref count changes you may need to pass [x.length]
as "a deps array" and create refs dynamically: Array.from({ length: x.length }).map(() => createRef()),
Usage:
refs[i+1 % 3].current.focus();