Categories
React

How to Get an Array of DOM Elements with React useRef hook?

Spread the love

Sometimes, we want to assign a ref to an array of rendered DOM elements in our React component.

In this article, we’ll look at how to get an array of DOM elements with the React useRef hook.

Create an Array of Refs and Store it in a Ref

We can create an array of refs and store it in an array of refs.

For instance, we can write:

import React, { useEffect, useRef } from "react";

const arr = ["left", "right"];
export default function App() {
  const refs = useRef(arr.map(() => React.createRef()));

  useEffect(() => {
    refs.current[0].current.focus();
  }, []);

  return (
    <div>
      {arr.map((el, i) => (
        <p key={i}>
          <input ref={refs.current[i]} value={el} onChange={() => {}} />
        </p>
      ))}
    </div>
  );
}

We call the useRef hook with the arr.map callback to map arr to an array of refs that we create with React.createRef .

Then we have a useEffect callback that calls refs.current[0].current.focus() to focus on the first element when App mounts.

Finally, we assign the refs in the map callback by assigning the ref property’s value to refs.current[i] .

Now when we mount the component, we should see the first input element having focus.

Alternatively, we can use the useMemo hook to cache the refs by writing:

import React, { useEffect, useMemo } from "react";

const arr = ["left", "right"];
export default function App() {
  const refs = useMemo(() => arr.map(() => React.createRef()), []);

  useEffect(() => {
    refs[0].current.focus();
  }, []);

  return (
    <div>
      {arr.map((el, i) => (
        <p key={i}>
          <input ref={refs[i]} value={el} onChange={() => {}} />
        </p>
      ))}
    </div>
  );
}

We create the refs the same way, but we wrap the callback with useMemo to cache the created refs.

Then we assign the refs and use them as we did in the previous example.

Conclusion

We can create an array of refs with the createRef function and the useMemo or useRef hook to store them.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *