0

I am calling a function in my react component

<button onClick={this.createComment}>Submit Comment</button>

Inside my createComment function 'this' is undefined for some reason

createComment(event) {
    console.log('inside createComment')
    console.log('event', event)
    console.log('this', this)

    event.preventDefault()
  }

I need to call this.setState inside the createComment function. How do I get the this to be the this of the component??

preston
  • 3,721
  • 6
  • 46
  • 78

1 Answers1

2

change this :

onClick={this.createComment}

to

onClick={(e) => this.createComment(e)}

OR

onClick={this.createComment.bind(this)}

NOTE :

As @rafahoro commented :

You should prefer to bind "this" on the constructor:

constructor() { 
     this.createComment = this.createComment.bind(this); 
} 

Using "onClick={(e) => this.createComment(e)}" or similar, will create a new function on each render() call.

Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122
  • Either use `arrow function` or `.bind(this)` `onClick={(e) => this.createComment(e)}` – Shubham Khatri Nov 08 '17 at 06:34
  • @ShubhamKhatri, thanks – Vivek Doshi Nov 08 '17 at 06:35
  • 1
    You should prefer to bind "this" on the constructor: constructor() { this. createComment = this. createComment.bind(this); } Using "onClick={(e) => this.createComment(e)}" or similar, will create a new function on each render() call. – rafahoro Nov 08 '17 at 06:47