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??

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Either use arrow function or .bind(this) onClick={(e) => this.createComment(e)}
@ShubhamKhatri, thanks
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.