Ad

Why Is My React Checkbox OnChange Handler Firing On Render And Then Not When The Box Is Clicked?

- 1 answer

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!

Ad

Answer

Because you're already calling the method on render.

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

Ad
source: stackoverflow.com
Ad