0

I am a React newbie, and am working on examples from Adam Freeman's book.

I am starting with simple event handling and am unable to figure out why the regular-looking version of handleClick() below does not work. The method using the arrow notation (from the book) works as expected, but I am trying to translate it to the standard method notation, and am unable to figure out what is missing.

import React, { Component } from "react";

export default class App extends Component {

constructor(props) {
super(props);
this.state = {
  count: 4
 }
}

isEven(val) { return val % 2 === 0 ? "Even" : "Odd"; }

// the following works
//handleClick = () => this.setState({ count: this.state.count + 1 });

// this gives an error: TypeError: Cannot read property 'setState' of undefined
handleClick() {
  this.setState({ count: this.state.count + 1 });
}

render = () =>
<h4>
  <button onClick={this.handleClick}>Click me!</button>
  Number of items: {this.isEven(this.state.count)}
</h4>
}

What changes are needed for handleclick() to work?

Manish
  • 1,726
  • 3
  • 23
  • 29
  • 1
    You need to bind it in constructor as `this.handleClick = this.handleClick.bind(this)`; – Meet Zaveri May 02 '19 at 10:25
  • I would use arrow function when declare the click function: `handleClick = () => this.setState({})` – knightburton May 02 '19 at 10:27
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Estus Flask May 02 '19 at 10:30

1 Answers1

1

You can bind this using one of the below,

In Constructor,

constructor(props) {
super(props);
this.state = {
  count: 4
 }
this.handleClick = this.handleClick.bind(this);
}

Or you can directly bind this as,

<button onClick={this.handleClick.bind(this)}>Click me!</button>

Or simply using fat arrow syntax,

<button onClick={() => this.handleClick()}>Click me!</button>

Ref

ravibagul91
  • 20,072
  • 5
  • 36
  • 59
  • Thanks very much, don't quite understand yet how this works. but it works. Probably some more experience will help. – Manish May 03 '19 at 01:43