Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my React checkbox onChange handler firing on render and then not when the box is clicked?

Have read through the React docs and boiled the problem down to a simple case, still can't quite understand what I'm doing wrong.

JSFiddle: https://jsfiddle.net/justin_levinson/pyn7fLq5/ or written below:

var TestForm = React.createClass({
    render : function() {
        return (
            <div>
                <p>Test Form</p>
                <form>
                    <TestBox />
                </form>
            </div>
        )
    }
});

var TestBox = React.createClass({
    render : function() {
        return (<input type="checkbox" name={"testbox"} defaultChecked={true} onChange={this.handleCheck()}/>)
    },
    handleCheck : function(event) {
        console.log("check");
        console.log(event);
    }
});

When the page loads, I get a 'check' in the log followed by 'undefined' for the event, then it doesn't fire again on subsequent clicks. Have tried this with both onClick and onChange as well as creating a controlled (checked={true}) instead of the uncontrolled (defaultChecked={true}) above.

Thanks!

like image 878
localtalent Avatar asked Jan 22 '16 00:01

localtalent


2 Answers

Because you're already calling the method on render.

change onChange={this.handleCheck()} to onChange={this.handleCheck}

like image 90
oobgam Avatar answered Sep 27 '22 16:09

oobgam


For anyone reading this in the future (like me), you can also solve this by formatting like onClick={(e) => this.handleCheck(parameter)} if you need to pass in a parameter.

like image 26
David Avatar answered Sep 27 '22 17:09

David