Sometimes, we want to set focus on an input field after rendering with React.
In this article, we’ll look at how to set focus on an input field after rendering with React.
Set Focus on an Input Field After Rendering with React
To set focus on an input field after rendering with React, we can assign a ref to the input element with the useRef
hook.
Then we call focus
on the current
value of the ref to focus on the input.
For instance, we write:
import React, { useEffect, useRef } from "react";
export default function App() {
const inputReference = useRef(null);
useEffect(() => {
inputReference.current.focus();
}, []);
return (
<div>
<input ref={inputReference} />
</div>
);
}
to call useRef
to create a ref and assign it to inputReference
.
Then we call inputReference.current.focus()
in the useEffect
callback to focus on the input.
inputReference.current
will be set to the input element when we set inputReference
as the value of the ref prop of the input.
We pass in an empty array as the 2nd argument so that the useEffect
callback only runs when the component mounts.
Finally, we assign the inputReference
ref to the input by setting it as the value of the ref
prop.
Conclusion
To set focus on an input field after rendering with React, we can assign a ref to the input element with the useRef
hook.
Then we call focus
on the current
value of the ref to focus on the input.
One reply on “How to Set Focus on an Input Field After Rendering with React?”
For anyone who lands here and are using material ui TextFields, you’ll need to change the code to dig down into the control to locate the input before you try and focus it. The ref will point to the TextField outer shell but the input lies a few layers down inside that control.
This is the way I changed the setFocus method to handle this kind of control:
const setFocus = () => {
if (ref.current) {
const inputs = (ref.current as HTMLElement).getElementsByTagName('input');
if (inputs.length) {
(inputs.item(0) as HTMLInputElement).focus();
}
}
}
Also, I’m using Typescript, thus the more typy code above.