Home Ask Login Register

Developers Planet

Your answer is one click away!

daremkd February 2016

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/

Answers


CookieOfFortune February 2016

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.


Nathan Hagen February 2016

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)} />
    );
}

Post Status

Asked in February 2016
Viewed 3,740 times
Voted 10
Answered 2 times

Search




Leave an answer


Quote of the day: live life