Home > Article > Web Front-end > How to Set Input Field Focus in React?
Setting Input Field Focus in React
When managing user interaction within a React application, it's often necessary to direct their focus to specific input fields after page rendering. The question arises on the best way to achieve this.
The documentation for React recommends using refs: To do so, attach a ref attribute to the input field, such as "nameInput," within the render function. Subsequently, you can call the method, "this.refs.nameInput.getInputDOMNode().focus();" to bring the input field into focus.
However, this method introduces the question of where to place this call. Dhiraj's response provides a viable solution: placing the focus call in the React lifecycle method componentDidMount().
Alternatively, for ease of use, you can leverage the autoFocus prop to automatically bring an input into focus when it mounts:
/>
Note that in JSX, the autoFocus prop is written with a capitalized F, unlike in plain HTML, where it is case-insensitive.
The above is the detailed content of How to Set Input Field Focus in React?. For more information, please follow other related articles on the PHP Chinese website!