Home >Web Front-end >JS Tutorial >How to Set Focus on an Input Field After Rendering in React?
React provides several methods for setting focus on an input field after the component has been rendered.
Option 1: Refs
As mentioned in the documentation, you can use a ref to access the DOM node of the input field. This can be done by setting the ref attribute on the input field in the render function:
<input ref="nameInput" ... />
Then, after the component has mounted, you can use the focus() method on the DOM node to set focus:
componentDidMount() { this.refs.nameInput.getInputDOMNode().focus(); }
Option 2: AutoFocus
You can also use the autoFocus prop to have an input automatically focus when mounted:
<input autoFocus name=... />
Note that in JSX, autoFocus must be capitalized, unlike in plain HTML where it is case-insensitive.
By utilizing either of these options, you can easily set focus on a particular text field after rendering, ensuring user convenience and enhancing the user experience.
The above is the detailed content of How to Set Focus on an Input Field After Rendering in React?. For more information, please follow other related articles on the PHP Chinese website!