How to focus an input element on page load?

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 (
<div>
<input defaultValue={"Won't focus"} />
<input ref={(input) => (this.nameInput = input)} defaultValue={'Will focus'} />
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));

Author of content
Edit this page

Made by Michael Sakhniuk

Twitter