Hello everyone ๐
Today I'm going to show you how to ref multiple elements like
const cards = document.querySelectorAll('.card');
in React JS using useRef()
hooks
Okay before wasting time too much, let's get right into the content
Imagine I've 3 <h1>
elements like this
<div>
<h1>Text Element 1</h1>
<h1>Text Element 2</h1>
<h1>Text Element 3</h1>
</div>
Then I want to ref multiple <h1>
elements using only one useRef()
hook
First, you must set the current value to an Array
// js
const ref = useRef([])
// ts (use HTMLHeadingElement to prevent the error)
const ref = useRef<HTMLHeadingElement[]>([])
Second, create a function to push elements into the array
// Js
const pushRef = (el) => ref.current.push(el)
// ts
const pushRef = (el: HTMLHeadingElement) => ref.current.push(el!) // using ! if you get an error 'object is possibly null'
Then, use the pushRef
function into an element
<div>
<h1 ref={pushRef}>Text Element 1</h1>
<h1 ref={pushRef}>Text Element 2</h1>
<h1 ref={pushRef}>Text Element 3</h1>
</div>
And yap, you're done. Let's check whether it works or not using the useEffect
hook
useEffect(() => {
if(ref.current) console.log(ref.current)
}, [ref])
Go to developer tools and check the console
The final code should look like this
Conclusion
When you try to ref
multiple elements in React you can just create an array and push the elements into the array
ReferenceStackoverflow
FYI: Iโm currently learning to writing in English for my IELTS. I try my best to write this article without any Copy and Paste generated text from an AI. If there is any wrong grammar, feel free to correct me. This Post is going to be my witness for my future self that Iโm willing to learn and growth ๐