JAVASCRIPT
Focus an Input Field on Component Mount with useRef
Learn how to programmatically focus an input field using the `useRef` hook in React, perfect for enhancing user experience on specific form elements.
import React, { useRef, useEffect } from 'react';
function FocusInputComponent() {
const inputRef = useRef(null);
useEffect(() => {
// Focus the input field when the component mounts
if (inputRef.current) {
inputRef.current.focus();
}
}, []); // Empty dependency array ensures it runs once on mount
return (
<div>
<label htmlFor="my-input">Your Name:</label>
<input id="my-input" type="text" ref={inputRef} placeholder="Type here..." />
</div>
);
}
export default FocusInputComponent;
How it works: The `useRef` hook creates a mutable `ref` object that persists across renders. It's often used to access DOM elements directly. Here, `inputRef` is attached to the `<input>` element. Inside `useEffect`, which runs after the component mounts, we check if `inputRef.current` (which will be the actual DOM input element) exists and then call its `focus()` method to programmatically set the focus.