Last updated: Apr 7, 2024
Reading time·2 min
To focus input when another element is clicked in React:
ref
prop on the input element.onClick
prop on the other element.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;
We used the useRef hook to create a ref object that gives us access to the input element.
const ref = useRef(null);
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.
current
property on the ref object to get access to the input
element on which we set the ref
prop.const handleClick = () => { ref.current.focus(); };
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.
onClick
prop on a button element, so every time the button is clicked, the handleClick
function is invoked.<button onClick={handleClick}>Focus input</button>
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.
ref.current.focus();
The current
property on the ref gives us access to the input
element, so
calling ref.current.focus()
sets the focus on the input.
Here is an example of focusing an input element when a div
gets clicked.
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 /> <hr /> <hr /> <div style={{backgroundColor: 'lime'}} onClick={handleClick} > bobbyhadz.com </div> </div> ); }; export default App;
This time we added the onClick
event listener on a div
element.
Every time the div
gets clicked, the handleClick
function is invoked.
const handleClick = () => { ref.current.focus(); };
All we have to do is use the ref
to focus the input
element in the body of
the handleClick
function.
If you need to check if an element is focused, click on the following article.
I've also written a tutorial on how to detect when the focus is lost.