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

How to Focus an Input Field in React After Rendering?

Linda Hamilton
Release: 2024-11-03 21:15:02
Original
418 people have browsed it

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

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="..." />
);
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!