Open In App

How to use useRef to Access & Interact with DOM eElements ?

Last Updated : 30 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In React, useRef is a Hook that provides a way to create mutable references to DOM elements or other React elements. It allows you to access and interact with these elements directly without manually querying the DOM. In this article, we’ll explore how to use useRef to work with DOM elements effectively in React applications.

Prerequisites:

Steps to Create React Application:

Step 1: Create a reactJS application by using this command

npx create-react-app myapp

Step 2: Navigate to the project directory

cd myapp

Project Structure:

Screenshot-2024-04-12-160925

The updated dependencies in package.json file will look like.

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

Accessing and interacting with DOM Elements

Though we have traditional DOM manipulation methods, useRef( ) is used to directly access DOM elements because it doesn’t
re-render the whole DOM. Instead, it renders the part which actually needs to be rendered for a particular action. To access any DOM elements, we use current property of ref object. Let us understand by taking some examples.

Example 1: This example will demonstrate how to access and interact with DOM elements.

JavaScript
//App.js

import React, { useRef } from "react";
function App() {
    //creates a reference to useRef 
    // hook with initial value set to null
    const ref_to_button = useRef(null);

    //function to change the button's color
    function handleclick() {
        if (ref_to_button.current) {
            //changes the button's color 
            // using useRef's current property
            ref_to_button.current.style.backgroundColor = "red";
        }
    }
    return (
        <div>
            <button ref={ref_to_button}
                onClick={handleclick}>
                Click me to turn me red
            </button>
        </div>
    );
}
export default App;

Steps to run application : Run the application using the following command from the root directory of the project

npm start

Output : Your output will be shown in the URL : http://localhost:3000/

ezgifcom-video-to-gif-converter

Changing button color to red using useRef() hook

Explanation

  • The useRef Hook initializes ref_to_button with a value of null.
  • When the button is clicked, the handleClick function sets the background color of the button using ref_to_button.current.style.backgroundColor = 'red'.
  • React compares the virtual DOM with the actual DOM, updates only the changed properties
    (in this case, the button’s background color), and avoids re-rendering other components, enhancing performance.

Example 2: Implementation toshow the change text content of a paragraph with another example.

JavaScript
//App.js

import React, { useRef } from "react";
function App() {
    // creates a reference to the 
    // useref hook and initially sets to null
    
    const paragraph_ref = useRef(null);
    // function to change the text 
    // when the button gets clicked
    
    const changeText = () => {
        if (paragraph_ref.current) {
            // changes the text content 
            // when the button gets clicked
            
            paragraph_ref.current.textContent =
                'This text is updated using useRef()';
        }
    };

    return (
        <div>
            <p ref={paragraph_ref}>
                Initial text
            </p>
            <button onClick={changeText}>
                Change Text
            </button>
        </div>
    );
}
export default App;

Steps to run application : Run the application using the following command from the root directory of the project

npm start

Output : Your output will be shown in the URL : http://localhost:3000/

ezgifcom-video-to-gif-converter-(1)

Manipulating the text using useRef( ) hook

Explanation:

  • The useRef Hook initializes paragraph_ref with a value of null.
  • The paragraph reference is attached to the <p> tag using the ref attribute.
  • When the button is clicked, the changeText function is called, updating the text content of the paragraph using paragraph_ref.current.textContent.
  • This overrides the initial text content with the new text provided in the function call, demonstrating how to access and manipulate DOM elements using the useRef() Hook.

Conclusion

useRef is a powerful tool in React for accessing and interacting with DOM elements. Whether you need to manage focus, access input values, interact with third-party libraries, or perform other DOM-related tasks, useRef provides a convenient and efficient way to achieve your goals while maintaining the declarative nature of React components.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads