본문 바로가기

Frontend/React

Hooks - useRef (Creating a Reference to Elements)

반응형

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

 

React

React is the most papular framework followed by Angular and Vue. React, like Angular uses components to build an application. However, React does not come with native features like Angular. Instead, it uses other libraries which makes React compact and sma

jin-co.tistory.com

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

Traversy Media - YouTube

 

Traversy Media

Traversy Media features the best online web development and programming tutorials for all of the latest web technologies from the building blocks of HTML, CSS & JavaScript to frontend frameworks like React and Vue to backend technologies like Node.js, Pyth

www.youtube.com

 

728x90
반응형