TypeError: Cannot read property ‘setState’ of undefined in React [duplicate]

  javascript, reactjs

I am currently trying to make a component in React that increments a state value when a button is pressed and displays the value in the button’s content. However, I keep getting a TypeError: Cannot read property 'setState' of undefined.

I’ve seen some other answers here saying to use things this.delta = this.delta.bind(this);, but they haven’t worked for me.

If anyone knows how I could fix my code, any help would be greatly appreciated!

class Practice extends React.Component {
  constructor(props) {
    super(props);
    this.state = {clicks : 0};
    this.delta = this.delta.bind(this);
  }
  render() {
    return (
  <div className="info">
    <TitleBar />
    <div className="box">
      <h3>You</h3>
    </div>
    <div className="box">
      <h2 className="">Title</h2>
      <button className="clickpad" onClick={addClick}>{this.state.clicks}</button>
    </div>
  </div>
    )
  }
}

function addClick() {
  this.setState({clicks: this.state.clicks + 1})
}

export default Practice;

Source: Ask Javascript Questions

LEAVE A COMMENT