Set focus on input after render in React.js

Let’s see how to set focus on input after a component is rendered. Use componentDidMount and refs callback to focus on the element.

componentDidMount(){

this.nameInput.focus();

}

Use it as shown below:

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'));


<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.js"></script>

<div id="app"></div>

This method works but there is a chance that it will not work if your component renders nothing first. You can solve this problem by adding this.refs.nameInput.getDOMNode.focus(); in componentDidMount. This problem is because the element is already mounted. You can also use

autoFocus when mounted.

<input autoFocus name=...

The setback is that it focuses input on any re-render which might not be desired.