1

I'm trying to get to work this code.

/*
 * A simple React component
 */
class Application extends React.Component {
    num = 42;
    render() {
      return (
        <button onClick={this.show}>show</button>
      );
    }
    componentDidMount() {
      console.log(this.num);
    }
    show() {
      console.log(this.num);
    }
}

/*
 * Render the above component into the div#app
 */
React.render(<Application />, document.getElementById('app'));

The problem is, when I click the button to get the property's value, it will be undefined. The interesting part is that the ComponentDidMount() function can access the num value.

I think that the show() function has different context, and that's why I can't refer to num via this keyword. I tried to bind the num value in the constructor, but it didn't work either, so I removed it.

Any idea how can I get the num value by clicking on the button?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
pkovzz
  • 353
  • 2
  • 5
  • 13
  • Related: [How to access the correct `this` / context inside a callback?](http://stackoverflow.com/q/20279484/218196) – Felix Kling May 19 '16 at 13:41

3 Answers3

2

You can use either an arrow function

<button onClick={() => this.show()}>show</button>

or bind the value of this

<button onClick={this.show.bind(this)}>show</button>

to get the correct num

Ref:

Arrow functions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Function.bind: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Pete TNT
  • 8,293
  • 4
  • 36
  • 45
1

Since you are using ES6 syntax, React doesn't autobind this to your method see :

https://facebook.github.io/react/docs/reusable-components.html#no-autobinding

And for more way to do this binding see this :

http://egorsmirnov.me/2015/08/16/react-and-es6-part3.html

edit : accepted answer provide bad practice see this : https://daveceddia.com/avoid-bind-when-passing-props/

0xCrema.eth
  • 887
  • 1
  • 9
  • 22
0

You are right - the show function has a different context.

You can solve solve this by binding the context to the onClick callback:

<button onClick={this.show.bind(this)}>show</button>

hakas
  • 125
  • 1
  • 6