Open In App

Explain how useRef helps us work with elements in the DOM?

useRef is like having a magic pointer in your functional components that helps you interact with elements in the HTML DOM (Document Object Model), which is essentially the structure of your webpage.

How does useRef works ?

Example: In this example:



This example shows us how useRef allows us to directly interact with DOM elements in a functional component, enabling us to manage focus on the input field without the need for a class component or maintaining state.




import React,
    { useRef } from 'react';
 
const FocusInput = () => {
    // Create a ref to hold a reference to the input element
    const inputRef = useRef(null);
 
    // Function to focus on the input field
    const focusInput = () => {
        // Focus on the input field when the button is clicked
        inputRef.current.focus();
    };
 
    return (
        <div>
            {/* Input field with ref attached */}
            <input type="text" ref={inputRef} />
            <button onClick={focusInput}>Focus Input</button>
        </div>
    );
};
 
export default FocusInput;

Output:



Output


Article Tags :