0
class App extends React.Component {
    method(){
        console.log(this);
    }   
    render(){
        return (<div>           
            <button onClick={this.method}>Try it</button>
        </div>)
    }
}

ReactDOM.render(<App/>, document.getElementById('demo'));

I think the button element is driving the method so the button element object should have been returned instead of undefined

Why so happens?Why you need to use this.method.bind(this) to have it worked?

chitra
  • 51
  • 1
  • 5
  • Suggested reading http://blog.andrewray.me/react-es6-autobinding-and-createclass/ – Andy Ray Dec 29 '16 at 14:34
  • Possible duplicate of [How does "this" keyword work within a function?](http://stackoverflow.com/questions/133973/how-does-this-keyword-work-within-a-function) – aghidini Dec 29 '16 at 14:35

1 Answers1

1

when the function passed to onClick is called, it is called with the scope of the DOM element that was clicked, this is the DOM element. In order to get the this reference you want, you will need to create a new function which passes the reference as this. There is a handy built in method just for this, bind. You can set up the bind in the constructor like so:

class App extends React.Component {
    constructor (props) {
        super(props);
        this.method = this.method.bind(this);
    }
    method(){
        console.log(this);
    }   
    render(){
        return (<div>           
            <button onClick={this.method}>Try it</button>
        </div>)
    }
}

ReactDOM.render(<App/>, document.getElementById('demo'));
TheSharpieOne
  • 25,646
  • 9
  • 66
  • 78