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.