SoFunction
Updated on 2025-04-07

Detailed explanation of the use of React autofocus fields

text

Autofocus can make your application more user-friendly, and there are several ways to automatically focus the React input box.

The easiest way to make the input box automatically focus is to useautoFocusProperties (note case):

<input name="username" type="text" autoFocus />

Since this property works inconsistently in different browsers, React implements a polyfill internally, which will be used when the element is mounted.focus()method.

But this is not always useful, we need to encapsulate one ourselves.

There are two ways to implement it:

  • useuseCallback()
  • useuseRef()anduseEffect()

We'll write it into a Hooks so that we can reuse it in the project.

Use useCallback()

useCallback()The hook returns a memorized callback function. It accepts two parameters. The first is the function to be run, and the second is the array of values ​​that the function depends on.

import { useCallback } from 'react'
const useAutoFocus = () => {
  const inputRef = useCallback((inputElement) => {
    if (inputElement) {
      ()
    }
  }, [])
  return inputRef
}
export default useAutoFocus

NoteduseCallbackThe second parameter of  is an empty array, which means that the function only runs once when the component is rendered.

When the form component renders, a reference to the input box is set. It executesuseCallback()Function in the hook, which calls the input boxfocus()

Use useRef() and useEffect()

useffect()The hook will tell React that after the component renders, you need the component to perform some operations. It accepts two parameters. The first is the function to be run, and the second is an array of dependencies, whose functions are asuseCallback()The same in  .

useRef()The role of hooks on function components andcreateRef()The same effect on class-based components. This hook creates a plain JavaScript object that you can pass to an element to keep a reference to it. Can be passed through the objectcurrentAttributes access this reference.

import { useRef, useEffect } from 'react'
const useAutoFocus = () => {
  const inputRef = useRef(null)
  useEffect(() => {
    if () {
      ()
    }
  }, [])
  return inputRef
}
export default useAutoFocus

In the above code, we create a reference to the input box. Then, when the component renders, we use the reference object'scurrentThe property call input boxfocus()

Example of usage

import { useState, useEffect } from 'react'
import ReactDOM from 'react-dom'
import useAutoFocus from './hooks/useAutoFocus'
function App() {
  const emailInput = useAutoFocus()
  return (
    &lt;&gt;
      &lt;form&gt;
        &lt;label&gt;
          user
          &lt;input name='username' type='text' ref={emailInput} /&gt;
        &lt;/label&gt;
        &lt;label&gt;
          password
          &lt;input name='password' type='password' /&gt;
        &lt;/label&gt;
        &lt;button type='submit'&gt;Log in&lt;/button&gt;
      &lt;/form&gt;
    &lt;/&gt;
  )
}
(&lt;App /&gt;, ('root'))

More information

React Hooks

The above is the detailed explanation of the use of React autofocus fields. For more information about React autofocus fields, please follow my other related articles!