How to focus an input element on page load in React?

To focus an input element on page load in React, you can use the useRef hook and the useEffect hook to create a reference to the input element and focus it when the component mounts. Here's an example:

import React, { useRef, useEffect } from 'react';
function MyInput() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
}, []);
return <input ref={inputRef} />;
}

In the example above, the useRef hook is used to create a reference to the input element, and the useEffect hook is used to focus the input when the component mounts. The useEffect hook is called with an empty array as the second argument, which means it will only run when the component mounts.

You can also use the autoFocus prop on the input element itself to focus the input when the component mounts, like this:

import React from 'react';
function MyInput() {
return <input autoFocus />;
}

This approach is simpler and may be preferred in some cases. However, using the useRef and useEffect approach allows you to control the focus behavior more explicitly and provides more flexibility in your code.


October 26, 2022
8465