JAVASCRIPT
React useRef for Direct DOM Manipulation
Learn how to use the React useRef hook to directly access DOM elements, such as focusing an input field, for imperative interactions in functional components.
import React, { useRef } from 'react';
function FocusInput() {
const inputRef = useRef(null);
const handleFocusClick = () => {
if (inputRef.current) {
inputRef.current.focus();
}
};
return (
<div>
<input type="text" ref={inputRef} placeholder="Click button to focus me" />
<button onClick={handleFocusClick}>Focus Input</button>
</div>
);
}
export default FocusInput;
How it works: The `useRef` hook in React allows you to create mutable references that persist across re-renders. It's commonly used to access and interact with DOM elements directly, as shown in this example where `inputRef` is attached to an input element. When the button is clicked, `inputRef.current.focus()` imperatively focuses the input field, which is a pattern often needed for form interactions or integrating with third-party DOM libraries without causing re-renders.