Home > Web Front-end > JS Tutorial > body text

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

DDD
Release: 2024-11-03 07:53:30
Original
1018 people have browsed it

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

Using Multiple Refs for an Array of Elements with Hooks

The useRef hook provides a persistent reference to an element in your React component. It allows you to directly access and modify DOM elements. In the case of a single element, using useRef is straightforward. However, what if you want to use multiple refs for an array of elements?

The Problem

Consider the following code:

<code class="js">const { useRef, useState, useEffect } = React;

const App = () => {
  const elRef = useRef();
  const [elWidth, setElWidth] = useState();

  useEffect(() => {
    setElWidth(elRef.current.offsetWidth);
  }, []);

  return (
    <div>
      {[1, 2, 3].map(el => (
        <div ref={elRef} style={{ width: `${el * 100}px` }}>
          Width is: {elWidth}
        </div>
      ))}
    </div>
  );
};

ReactDOM.render(
  <App />,
  document.getElementById("root")
);</code>
Copy after login

This code will cause an error because elRef.current is not an array. It is a reference to the first element in the array.

The Solution with an External Ref

A possible solution to this problem is to use an external reference to keep track of multiple elements. Here's an example:

<code class="js">const itemsRef = useRef([]);

const App = (props) => {
  useEffect(() => {
    itemsRef.current = itemsRef.current.slice(0, props.items.length);
  }, [props.items]);

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

In this case, itemsRef.current is an array that holds references to all the elements in the array. You can access these elements using itemsRef.current[n].

Note: It's important to remember that hooks cannot be used inside loops. Therefore, the useEffect hook is used outside the loop to update the itemsRef array.

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template