3
votes

I can not figure out if I am missing something small here?

Just trying to get a grasp on how state works with React.

Just creating a small check box that changes text on check/uncheck.

import React from 'react';

export default class Basic extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            checked: true
        };
    }

    handleCheck() {
        this.setState = ({
            checked: !this.state.checked
        });
    }

    render() {
        var msg;
        if (this.state.checked) {
            msg = 'checked'
        } else {
            msg = 'unchecked'
        }
        return (
            <div>
                <input type="checkbox" onChange={this.handleCheck} defaultChecked={this.state.checked} />
                <h3>Checkbox is {msg}</h3>
            </div>
        );
    }
}
2
because you forgot to bind the onChange method, use this: onChange={this.handleCheck.bind(this)} or bind the method in the constructor. - Mayank Shukla
So I added that then I got this "Uncaught TypeError: inst.setState.bind is not a function" - JontheNerd
can you show what you changed ? you don't need to bind the setState you need to bind the onChange method like i suggested in above comment, just replace the onChange method with the above line. - Mayank Shukla
render() { var msg; if(this.state.checked) { msg = 'checked' }else { msg = 'unchecked' } return ( <div> <input type="checkbox" onChange={this.handleCheck.bind(this)} defaultChecked={this.state.checked} /> <h3>Checkbox is {msg}</h3> </div> ); } - JontheNerd
you used setState in awrong way, remove = in this line: this.setState = ({ it should be this.setState({ - Mayank Shukla

2 Answers

9
votes

Changes:

1. You forgot to bind the onChange method, either use this:

onChange={this.handleCheck.bind(this)}

or define the binding in the constructor:

this.handleCheck = this.handleCheck.bind(this)

2. You used setState in a wrong way, setState is a method you need to call it.

Instead of: this.setState = ({})

it should be: this.setState({})

5
votes

Binding your handleCheck function in the constructor:

constructor(props) {
    super(props);

    this.state = {
        checked: true
    };

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