Focus input when another Element is clicked in React


Borislav Hadzhiev

Last updated: Apr 24, 2022


Photo from Unsplash

Focus input when another Element is clicked in React #

To focus input when another element is clicked in React:

  1. Set the ref prop on the input element.
  2. Set the onClick prop on the other element.
  3. When the other element is clicked, focus the input, e.g. ref.current.focus().
import {useRef} from 'react'; const App = () => { const ref = useRef(null); const handleClick = () => { ref.current.focus(); }; return ( <div> <input ref={ref} id="message" name="message" /> <hr /> <button onClick={handleClick}>Focus input</button> </div> ); }; export default App;

focus input on button click

We used the useRef hook to create a ref object that gives us access to the input element.

The useRef() hook can be passed an initial value as an argument. The hook returns a mutable ref object whose .current property is initialized to the passed argument.

Notice that we have to access the current property on the ref object to get access to the input element on which we set the ref prop.

When we pass a ref prop to an element, e.g. <input ref={myRef} />, React sets the .current property of the ref object to the corresponding DOM node.

We set the onClick prop on a button element, so every time the button is clicked, the handleClick function is invoked.

Note that this doesn't have to be a button, you can set the onClick prop on a div or any other element.

We used the focus() method to focus the input field in the handleClick function.

The current property on the ref gives us access to the input element, so calling ref.current.focus() sets the focus on the input.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.