DEV Community

Thang Truong
Thang Truong

Posted on

Multiple item using one ref

Some cases in ReactJS, we need use a variable declared by useRef for items, components, ....

How to use

First, you need variable declared by useRef and
and set initialValue to be an empty array []

const exampleRef = useRef([]);
Enter fullscreen mode Exit fullscreen mode

Create a function to add item, component to exampleRef

const addToRefs = el => {
    if (el && !exampleRef.current.includes(el)) {
       exampleRef.current.push(el);
    }
};
Enter fullscreen mode Exit fullscreen mode

Then you just add ref to item, component, ...

<div ref={addToRefs}>                 
</div>
Enter fullscreen mode Exit fullscreen mode

Now, exampleRef.current as an array, you can use methods with array to use for exampleRef like map, forEach, ...

Discussion (0)