Sometimes, we want to set focus on an input field after rendering with Reatct.
In this article, we’ll look at how to set focus on an input field after rendering with Reatct.
How to set focus on an input field after rendering with Reatct?
To set focus on an input field after rendering with React, we assign a ref to the input and then call focus
on the ref’s value.
For instance, we write
import React, { useEffect, useRef } from "react";
const MyForm = () => {
const textInput = useRef(null);
useEffect(() => {
textInput.current.focus();
}, []);
return (
<div>
<input ref={textInput} />
</div>
);
};
to define the MyForm
component.
In it, we call useRef
to create the textInput
ref.
And then we assign that as the value of the ref
prop of the input.
Then we call textInput.current.focus();
in the useEffect
hook callback to focus on the input.
The callback is called when the component is mounted since the 2nd argument is an empty array.
Conclusion
To set focus on an input field after rendering with React, we assign a ref to the input and then call focus
on the ref’s value.