FrontendDeveloper.in

React question detail

How to focus an input element on page load?

You need to use useEffect hook to set focus on input field during page load time for functional component.

import React, { useEffect, useRef } from "react";

const App = () => {
const inputElRef = useRef(null);

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

return (
<input defaultValue={"Won't focus"} />
<input ref={inputElRef} defaultValue={"Will focus"} />
);
};

ReactDOM.render(<App />, document.getElementById("app"));

See Class

You can do it by creating ref for input element and using it in componentDidMount():

class App extends React.Component {
componentDidMount() {
this.nameInput.focus();
}

render() {
return (
<input defaultValue={"Won't focus"} />
<input
ref={(input) => (this.nameInput = input)}
defaultValue={"Will focus"}
/>
);
}
}

ReactDOM.render(<App />, document.getElementById("app"));
Back to all React questions
Get LinkedIn Premium at Rs 399