HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptreactCritical

How to set focus on an input field after rendering?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
inputhowfieldsetafterfocusrendering

Problem

What's the react way of setting focus on a particular text field after the component is rendered?

Documentation seems to suggest using refs, e.g:

Set ref="nameInput" on my input field in the render function, and then call:

this.refs.nameInput.getInputDOMNode().focus();


But where should I call this? I've tried a few places but I cannot get it to work.

Solution

You should do it in componentDidMount and refs callback instead. Something like this

componentDidMount(){
   this.nameInput.focus(); 
}




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


{ this.nameInput = input; }}
defaultValue="will focus"
/>

);
}
}

ReactDOM.render(, document.getElementById('app'));



Code Snippets

componentDidMount(){
   this.nameInput.focus(); 
}

Context

Stack Overflow Q#28889826, score: 810

Revisions (0)

No revisions yet.