localtalent
localtalent

Reputation: 87

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!

Upvotes: 7

Views: 7183

Answers (2)

David
David

Reputation: 972

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.

Upvotes: 10

oobgam
oobgam

Reputation: 1309

Because you're already calling the method on render.

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

Upvotes: 16

Related Questions