JAVASCRIPT
Auto-focusing an Input Field on Component Mount
Learn how to use the useRef and useEffect hooks in React to programmatically focus an input field or any DOM element when its component mounts.
import React, { useRef, useEffect } from 'react';
function AutoFocusInput() {
const inputRef = useRef(null);
useEffect(() => {
// Focus the input element when the component mounts
if (inputRef.current) {
inputRef.current.focus();
}
}, []); // Empty dependency array ensures this runs only once after initial render
return (
<div>
<label htmlFor="autoFocusInput">Your Name:</label>
<input
id="autoFocusInput"
type="text"
ref={inputRef}
placeholder="Type here..."
/>
</div>
);
}
export default AutoFocusInput;
How it works: This snippet demonstrates how to use `useRef` to get a direct reference to a DOM element (in this case, an input field) and `useEffect` to perform side effects. The `inputRef` is initialized with `null` and then attached to the input element via the `ref` prop. When the component mounts, the `useEffect` hook runs, and `inputRef.current` will point to the actual DOM node. We then call the `focus()` method on this DOM node to automatically set the cursor in the input field. The empty dependency array `[]` ensures this effect runs only once after the initial render, mimicking `componentDidMount`.