How to Focus on Input Fields with React Hooks

We need direct access to the DOM elements to focus on the input fields. Here, I make use of the hook useRef to achieve this. Let us see in action.

const inputRef = useRef(null)

First of all, I initiated a constant with useRef hook.

<input type="text" ref={inputRef} />

Then, I added our initiated value as a ref to one of my input field.

inputRef.current.focus()

Now, we have access to our input field as the variable inputRef. By this way, it’s possible to focus on that particular input field.

Final Code
import React, { useEffect, useRef } from 'react';

const App = () => {

  const inputRef = useRef(null)

  useEffect(() => {
    inputRef.current.focus()
  }, [])

  return (
    <form>
      <input type="text" ref={inputRef} />
    </form>
  );
}

export default App;

Since we have added the focus function inside the useEffect hook, Input field will be focused at the time of rendering the component.

Similar Posts

Leave a Reply