<!-- begin snippet: js hide: false console: true babel: true -->
<!-- language: lang-js -->
class XY extends React.Component{
componentDidMount(){
this.focusInput.focus();
}
render() {
return(
<div>
<input
ref={(input) => { this.focusInput = input; }}
defaultValue="This input will focus"
/>
</div>
);
}
}
ReactDOM.render(<XY />, document.getElementById('root'));
<!-- language: lang-html -->
<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="root"></div>
<!-- end snippet -->
You should do it in `componentDidMount` and [`refs callback`][1] instead. Something like this
componentDidMount(){
this.nameInput.focus();
}
[1]: https://facebook.github.io/react/docs/refs-and-the-dom.html
<!-- begin snippet: js hide: false console: true babel: true -->
<!-- language: lang-js -->
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'));
<!-- language: lang-html -->
<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>
<!-- end snippet -->