7

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!

2 Answers 2

16

Because you're already calling the method on render.

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

2
  • 2
    What if you need to send a parameter?
    – RMontes13
    Commented Jun 20, 2017 at 8:26
  • 2
    @RMontes13 this.handleCheck.bind(null, parameter)
    – oobgam
    Commented Jun 21, 2017 at 3:06
10

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.