← Back
html react

Autofocus input

In React, it's quite easy to force focus of an input when the component is mount:

const MyForm: React.FC = () => {
const ref = useRef<HTMLInputElement>();

useEffect(() => {
if (ref.current) {
ref.current.focus();
}
}, []);

return (
<form>
<input ref={ref} />
...
</form>
);
};

But recently I've learned (yes, I didn't know it!!!) the autofocus property:

const MyForm: React.FC = () => {
return (
<form>
<input autofocus />
</form>
);
};

More info: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#htmlattrdefautofocus

🖖