daremkd
daremkd

Reputation: 8424

Get refs via function call

I'm trying to replicate the React code from this official guide:

  render: function() {
    return <TextInput ref={(c) => this._input = c} />;
  },
  componentDidMount: function() {
    this._input.focus();
  },

Basically, I'm using ES5 and tried this:

 componentDidMount: function() {
        this.searchBox.focus();
    },

    render: function() {
        return (
            <input type="text" ref={function(c) {this.searchBox = c}} />
        );
    }

But I got an error saying:

Uncaught TypeError: Cannot read property 'focus' of undefined

Isn't the code above supposed to be the same like the ES6 version? I don't get it why it's not working. In case you're interested in the full code, here it is: https://jsfiddle.net/xpd85ehx/

Upvotes: 0

Views: 62

Answers (2)

Nathan Hagen
Nathan Hagen

Reputation: 12810

The es6 version uses arrow functions, which auto-binds the function to the existing scope. so for example,

function(c) {this.searchBox = c}

is not bound to the instance of the component, while

c => this.searchBox = c

is. In the first example, its hard to know what this is, but in the second, we can be pretty sure that this is a reference to our component`. If you want to make your solution work in es5, you need to manually bind, like this

render: function() {
    return (
        <input type="text" ref={(function(c) {this.searchBox = c}).bind(this)} />
    );
}

Upvotes: 1

CookieOfFortune
CookieOfFortune

Reputation: 14004

ES5 and ES6 arrow notations use a different this.

Specifically, using the arrow notation, this is lexically bound to the surrounding function (so it refers to the class).

Using ES5 you will need to bind this to your function.

Upvotes: 1

Related Questions