Dave Dave - 3 months ago 624
React JSX Question

React set focus on input after render

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.

Answer

For < react-0.13

You should do it in componentDidMount and getDOMNode() instead. Something like this

componentDidMount: function(){
   this.refs.nameInput.getDOMNode().focus(); 
},

<div id="main"></div>
<script src="http://fb.me/JSXTransformer-0.12.2.js"></script>
<script src="http://fb.me/react-0.12.2.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script type="text/jsx">
      /** @jsx React.DOM */
      var App = React.createClass({
        componentDidMount: function(){
          this.refs.nameInput.getDOMNode().focus(); 
        },
        render: function() {
            return(
              <div>
                <input name="two" value="Won't focus" />
                <input name="one" ref="nameInput" value="will focus"/>
              </div>
             );
        }
    });
    
      React.render(<App />, document.getElementById('main'));
    </script>

Here is a DEMO


Update (for > react-0.13)

React.findDOMNode has to be used since this.refs...getDOMNode() has been deprecated. It should look something like this

React.findDOMNode(this.refs.nameInput).focus(); 

Complete example

"use strict";
  class App extends React.Component{
    componentDidMount(){
      React.findDOMNode(this.refs.nameInput).focus(); 
    }
    render() {
        return(
          <div>
            <input name="two" value="Won't focus" />
            <input name="one" ref="nameInput" value="will focus"/>
          </div>
         );
    }
  }

  React.render(<App />, document.getElementById('app'));

here is an updated Demo

Update 2: Nowadays, it's:

var ReactDOM = require('react-dom');
componentDidMount(){
  ReactDOM.findDOMNode(this.refs.nameInput).focus(); 
}
Comments