The useRef hook allows you to interact with DOM elements directly in React without causing re-renders. One common use case is setting focus on an input field when the component mounts.
Example: Set Focus on an Input Field
-
Create a
reffor the input field:
const refContainer = useRef(null);
- Set focus after the component mounts:
useEffect(() => {
refContainer.current.focus();
}, []);
Full Example:
import { useEffect, useRef, useState } from 'react';
const App = () => {
// State to track the value
const [value, setValue] = useState(0);
// Creating a ref to access the input field
const refContainer = useRef(null);
// useEffect hook that runs after each render
// It focuses the input field every time the component re-renders
useEffect(() => {
refContainer.current.focus(); // Focuses the input field
});
// The code below could also use an empty dependency array to run only once after the first render:
// useEffect(() => {
// refContainer.current.focus(); // Focuses the input field after the component mounts
// }, []);
return (
<div>
<form>
{/* Attach the ref to the input field */}
<input type="text" ref={refContainer} />
</form>
{/* Display the current value */}
<h1>Value: {value}</h1>
{/* Button to increase the value */}
<button onClick={() => setValue(value + 1)}>Increase</button>
</div>
);
};
export default App;
Explanation:
useRef(null): Creates a reference to the input field, allowing direct DOM manipulation (e.g., setting focus).useEffect: Runs after every render. The code inside focuses on the input field usingrefContainer.current.focus(). If you want it to only run after the initial render, you could use an empty dependency array[].Input Field: The
ref={refContainer}attaches theuseRefto the input, giving you access to its DOM element.
Top comments (0)