DEV Community

Thang Truong
Thang Truong

Posted on

2 1

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, ...

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more