ReactJS – useRef hook


In this article, we are going to see how to create a reference to any DOM element in a functional component.

This hook is used to access any DOM element in a component and it returns a mutable ref object which will be persisted as long as the component is placed in the DOM.

If we pass a ref object to any DOM element, then the .current property to the corresponding DOM node elements will be added whenever the node changes.

Syntax

const refContainer = useRef(initialValue);

Example

In this example, we will build a React application that passes the ref object to two input fields.

When clicked on a button, it will automatically fetch the data of these input fields.

App.jsx

import React, { useRef } from 'react';

function App() {

   const email = useRef(null);
   const username = useRef(null);

   const fetchEmail = () => {
      email.current.value = 'rahul@gmail.com';
      email.current.focus();
   };
   const fetchUsername = () => {
      username.current.value = 'RahulBansal123';
      username.current.focus();
   };
   return (
      <>
         <div>
            <h1>Tutorialspoint</h1>
         </div>
         <div>
            <input placeholder="Username" ref={username} />
            <input placeholder="Email" ref={email} />
         </div>
         <button onClick={fetchUsername}>Username</button>
         <button onClick={fetchEmail}>Email</button>
      </>
   );
}
export default App;

In the above example, when the Username or Email button is clicked, the fetchUsername and fetchEmail function is called respectively which pass the ref object to the input fields and change its value from NULL to some text.

Output

This will produce the following result.

Updated on: 19-Mar-2021

453 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements