Home  >  Article  >  Web Front-end  >  How to Use Multiple Refs for an Array of Elements with React Hooks?

How to Use Multiple Refs for an Array of Elements with React Hooks?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-04 01:52:30260browse

How to Use Multiple Refs for an Array of Elements with React Hooks?

Using Multiple Refs for an Array of Elements with Hooks

Problem Statement:
Although using refs for a single element with hooks is straightforward, this becomes more complex when dealing with an array of elements.

Implementation:
To implement multiple refs for an array of elements using hooks, we can leverage the useRef hook as follows:

<code class="js">const App = () => {
  const itemsRef = useRef([]);//create a ref instance for array

  useEffect(() => {
    itemsRef.current = itemsRef.current.slice(0, props.items.length);
  }, [props.items]);//update the `itemsRef` array on any change of `props.items`

  return props.items.map((item, i) => (
    <div
      key={i}
      // pass the element ref to the `itemsRef` array
      ref={el => (itemsRef.current[i] = el)}
      style={{ width: `${(i + 1) * 100}px` }}
    >
      ...
    </div>
  ));
};</code>

Usage:
With this approach, you can access the elements in the array via itemsRef.current[index]. Unlike the example in the question, this ensures that the refs are correctly updated when the array changes.

Additional Notes:

  • Since hooks cannot be used within loops, the useEffect hook is used to update the itemsRef array on re-renders caused by changes in props.items.
  • The slice() method ensures that the itemsRef array contains only the elements corresponding to the current props.items array.

The above is the detailed content of How to Use Multiple Refs for an Array of Elements with React Hooks?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn