Here is an example of how to setState in ReactJS

Screen Shot 2017-08-25 at 10.21.50 AM.png

import React, { Component } from 'react';

class Counter extends Component {

    constructor(props) {
        super(props);

        this.state = {
            count : 1
        };

        this.delta = this.delta.bind(this);
    }

    delta() {
        this.setState({ count : this.state.count + 1});
    }

    render() {
      console.log('rendering...');
        return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.delta}>+</button></div>
);
    }
}

export default Counter;

Screen Shot 2017-08-25 at 10.28.46 AM.png

Note the key is this line right here:

Screen Shot 2017-08-25 at 10.24.11 AM.png

If you don’t set that. You will get this error:

TypeError: Cannot read property 'setState' of null

Screen Shot 2017-08-25 at 10.24.41 AM.png

Which means you have the wrong ‘this’ in your function. And you fix it by binding your function with the line of code shown above.

https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56

Advertisements