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

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

DDD
DDDOriginal
2024-11-03 10:23:02373browse

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

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

Introduction

Refs provide a way to access HTML elements in React components. While you can use refs to manage single elements, there may be situations where you need to apply refs to an array of elements. This article explores how to implement multiple refs for an array of elements using hooks in React.

Single Element Ref

Using refs for a single element is straightforward:

<code class="javascript">const elRef = useRef();
const [elWidth, setElWidth] = useState();

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

Array of Elements Ref

Applying the above approach to an array of elements will not work as it assigns the same ref to all elements. Instead, we need to create an array of refs and assign them individually to each element:

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

// Initialize the array of refs
useEffect(() => {
  itemsRef.current = itemsRef.current.slice(0, props.items.length);
}, [props.items]);

// Use the array of refs in JSX
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 solution, itemsRef.current is an array of references to the HTML elements. You can access individual elements by indexing the array, e.g., itemsRef.current[0].

The above is the detailed content of How Can I 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