From the course: Master React 19 and Next.js 16 with Hands-On Projects and Real-World Applications

Unlock this course with a free trial

Join today to access over 25,200 courses taught by industry experts.

Accessing a DOM node with ref

Accessing a DOM node with ref

In this session, we'll learn how to use React refs to focus an input field when a button is clicked. This is a powerful technique for improving user experience and creating interactive forms. You'll learn how to create and attach a ref, then access the DOM node to manipulate it. Let's start with a basic React template. Okay, let's add an input field and a button to our app.jsx component. Now you have an input field with a placeholder and a button. I've wrapped these elements in a div for structure. This sets up the basic HTML for our interaction. Now I am importing the useRef hook from React. This hook is essential for creating and managing refs in functional components. Now it is time to create our ref. I've declared a variable inputRef using the useRef function. This creates a ref object that we will later attach to our input element. Remember, useRef returns an object with a current property that will hold a reference to the DOM element. The null is the initial value. Here I am…

Contents