JAVASCRIPT
Auto-Focus an Input Field with useRef
Learn how to use React's `useRef` hook to programmatically focus an input field or interact directly with other DOM elements after component mounts.
import React, { useRef, useEffect } from 'react';
function MyAutoFocusInput() {
const inputRef = useRef(null);
useEffect(() => {
// Focus the input field when the component mounts
if (inputRef.current) {
inputRef.current.focus();
}
}, []); // Empty dependency array means this runs once after initial render
return (
<div>
<label htmlFor="autofocus-input">Enter your name:</label>
<input ref={inputRef} id="autofocus-input" type="text" placeholder="Your name" />
</div>
);
}
export default MyAutoFocusInput;
How it works: This snippet demonstrates how to use the `useRef` hook to get a direct reference to a DOM element. The `inputRef` is initialized to `null` and then assigned to the `ref` attribute of the input element. Inside a `useEffect` hook, we check if `inputRef.current` exists (meaning the element has been rendered) and then call its `focus()` method, causing the input to automatically receive focus when the component first mounts.