Home > Article > Web Front-end > 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>
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>
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!