Multiple Refs for an Array of Elements Using Hooks
In React, the useRef hook allows developers to manage DOM references to elements. Typically, refs are used to access a single element. However, this approach may not be suitable for arrays of elements.
To work with multiple refs for an array of elements using hooks, a slightly different approach is required. Let's consider the following situation:
<code class="javascript">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> ); };</code>
In this example, we attempt to create multiple refs by simply passing the same elRef to each element in the array. However, this approach will result in only the last element being referenced.
To overcome this issue, we can leverage the following technique:
<code class="javascript">const App = props => { const itemsRef = useRef([]); // you can access the elements with itemsRef.current[n] 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 improved solution, we use the itemsRef array to hold the refs. We initialize the array with an empty array. In the useEffect, we update the itemsRef array to match the length of the props.items array. This ensures that we have a corresponding ref for each item in the array.
Now, we can access individual element refs using itemsRef.current[n], where n is the index of the element in the array.
The above is the detailed content of How to manage multiple refs for an array of elements in React using hooks?. For more information, please follow other related articles on the PHP Chinese website!