Reputation:
I'm trying to implement a simple checkbox that changes its checked state (true/false) upon clicking. But it does nothing when I click it. For example, upon clicking the checkbox and console logging state.box1 after the click, it's still set to true instead of false. I got the code from Material UI's checkbox example, so I'm confused as to why it doesn't work for me. Any ideas?
state = {
box1: true,
};
handleChange = name => event => {
setState({ name: event.target.checked });
};
<div>
<Checkbox
value="box1"
checked={state.box1}
onChange={this.handleChange('box1')}
label="Primary"
/>
</div>;
Upvotes: 0
Views: 203
Reputation: 2868
Assuming Checkbox
component passes the event object to the onChange callback.
Your original handleChange
return a callback function but it does not bind to the component context. So your event object will most likely be undefined
when you click the checkbox.
you can modify the code to something like this.
// takes both the event object and
handleChange = (event, name) => {
setState([name]: event.target.checked);
};
<Checkbox
value="box1"
checked={state.box1}
onChange={(event) => handleChange(event, 'box1')}
label="Primary"
/>
Upvotes: 1