In React, the useRef
function returns an object with the argument stored under the key current
. Sometimes I'd like to use an array, e.g. to keep a list of references, like
const divsRef = useRef([]);
return Array.from({ length: n }, (_, i) => (
<div
ref={function (el) {
divsRef.current[i] = el;
}}
/>
));
but typing out current
all the time is cumbersome. If I do
const divsRef = useRef();
return Array.from({ length: n }, (_, i) => (
<div
ref={function (el) {
divsRef[i] = el;
}}
/>
));
instead, then the resulting object isn't iterable. Hence my question, is there an easy way to turn an object into an iterable array, without changing its identity (otherwise the object wouldn't persist between rerenders)? I got it iterable by doing Object.setPrototypeOf(divsRef, Object.getPrototypeOf([]))
but then [...divsRef]
always returns the empty array.