In vanilla JS, we can get elements by creating a reference to the DOM element to change them dynamically. On the other hand, in React, not only is not possible to use the document object in a component but also we can access the element directly and change the value of attributes.
But if there is a way to get access to elements as we do with vanilla JS in React, it would not hurt to have the skill under the belt. The useRef hook just makes it possible to do that and we will see how we can use it.
Setting Up a Project
Creating a React App
How to Use It?
Import the hook.
import { useRef } from 'react'
Create a variable to create a reference and initialize the hook.
Add the variable as a value of the attribute of the element you want to refer to.
ref={<var>}
Let's see what we get
It returns an object with the value current in it.
And the current represents the element.
<var>.current
Examples
Once, we get the reference we can use it to change the value of the attributes of the element as we do in the vanilla JS.
In this writing, we have seen how to use the useRef hook.
References
'Frontend > React' 카테고리의 다른 글
React - Style Libraries (Bootstrap) (0) | 2024.01.14 |
---|---|
Hooks - useEffect (Catching Changes in a Component) (0) | 2023.05.18 |
Hooks - useContext(Global State) (0) | 2023.05.15 |
React Hook - Redirection (React Router DOM) (0) | 2023.05.03 |
React Hooks - UseParams / UseSearchParams (React Router DOM) (0) | 2023.05.03 |