Home > Web Front-end > JS Tutorial > body text

How to Set Focus on an Input Field After Rendering in React?

Susan Sarandon
Release: 2024-11-03 07:41:30
Original
615 people have browsed it

How to Set Focus on an Input Field After Rendering in React?

Setting 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" ... />
Copy after login

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();
}
Copy after login

Option 2: AutoFocus

You can also use the autoFocus prop to have an input automatically focus when mounted:

<input autoFocus name=... />
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template