Home >Web Front-end >JS Tutorial >How to Use Multiple Refs for an Array of Elements with React 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:
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!