Home > Article > Web Front-end > How to Focus an Input Field in React After Rendering?
Focusing an Input Field in React Post-Rendering
In React, setting focus on an input field after rendering can be achieved through various methods.
One approach is to utilize refs as suggested in the documentation. By assigning a ref to the input field within the render function (e.g., "nameInput"), you can access its DOM node and manually invoke the focus method. However, it's crucial to understand where and when to call this function.
Calling Focus Function
The most straightforward location to call the focus function is the component's componentDidMount lifecycle method. This ensures that the focus is set after the component has been mounted in the DOM. The code would look like this:
import React, { useRef, useEffect } from "react"; const MyComponent = () => { const nameInputRef = useRef(); useEffect(() => { if (nameInputRef.current) { nameInputRef.current.focus(); } }, []); return ( <input ref={nameInputRef} name="..." /> ); }; export default MyComponent;
Autofocus Option
Alternately, you can utilize the autoFocus prop provided by React. By setting this prop to true on the input field, the component will automatically gain focus upon mounting.
return ( <input autoFocus name="..." /> );
Note that, in JSX, the property is autoFocus (with a capital F), unlike the case-insensitive HTML attribute.
The above is the detailed content of How to Focus an Input Field in React After Rendering?. For more information, please follow other related articles on the PHP Chinese website!