Home >Web Front-end >JS Tutorial >How to Set Focus on an Input Field After Rendering in React?

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

Susan Sarandon
Susan SarandonOriginal
2024-11-03 07:41:30662browse

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" ... />

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!

Statement:
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