JAVASCRIPT
Accessing and Manipulating DOM Elements with useRef
Learn how to use React's `useRef` hook to get a direct, mutable reference to a DOM element, enabling imperative interactions like focusing an input or playing media.
import { useRef } from 'react';
function FocusableInput() {
const inputRef = useRef(null);
const handleClick = () => {
// `inputRef.current` gives direct access to the DOM node
inputRef.current.focus();
inputRef.current.style.borderColor = 'blue';
};
return (
<div>
<input type="text" ref={inputRef} placeholder="Click button to focus me" />
<button onClick={handleClick}>Focus Input</button>
</div>
);
}
How it works: The `useRef` hook creates a mutable `ref` object whose `.current` property is initialized to the passed argument (e.g., `null`). When a `ref` object is attached to a DOM element (like `<input ref={inputRef} />`), `inputRef.current` will point directly to that DOM element. This allows for imperative operations such as focusing an input, managing media playback, or directly manipulating styles, which are outside of React's declarative data flow.