javascriptreactjselectron

React - Uncaught TypeError: Cannot read property 'state' of > null


I have the following piece of code. It is basically just a button with an event handler, and the class is supposed to hold some state which as of now is only a counter, set to 0 initially.

import React, { Component } from 'react';
// import styles from './SentenceView.css';

export default class SentenceView extends Component {

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

  getNextSentence() {
    console.log(this.state.count); // this &
    this.setState({count: 2}); // this gives me an error
    console.log("Executed");
  }

  render() {
    return (
      <div>
        {/* <div className={styles.container}> */}
        <div>
          <h1>SentenceView</h1>
          <button onClick={this.getNextSentence}>Next Sentence</button>
        </div>
      </div>
    );
  }
}

When I click the getNextSentence button I get:

SentenceView.js:14 Uncaught TypeError: Cannot read property 'state' of null

I am aware that this error is not uncommon, but I have not yet found any solution on here.


Solution

  • Try adding this to your constructor at the bottom:

    this.getNextSentence = this.getNextSentence.bind(this);