JAVASCRIPT
Direct DOM Interaction with React's useRef for Focus Management
Learn how to use React's `useRef` hook to directly interact with DOM elements, such as managing focus for input fields, useful for accessibility and user experience.
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="Focus me!" />
<button onClick={handleFocusClick}>Set Focus on Input</button>
<p>Click the button to programmatically set focus on the input field above.</p>
</div>
);
}
export default FocusInput;
How it works: The `useRef` hook allows you to create a mutable `ref` object whose `.current` property can hold any mutable value. It's commonly used to access a DOM element directly, bypass React's virtual DOM, or store a value that persists across renders without causing a re-render when it changes. In this example, `inputRef` is attached to an input element, and its `current` property is then used to call the `focus()` method on the actual DOM node, demonstrating direct DOM manipulation.