Trying to use Material UI checkbox. Pretty simple one might think? Well the checkbox doesn't toggle. Turns out the onChange event is not fired even internally to the component (I put logs in the node_modules package).
<Checkbox
checked={this.state.isTrue}
onChange={e => {
console.log(e.target.checked);
this.setState({isTrue: e.target.checked});
}} />
Pretty simple, right? But the console.log
never fires. I can hack around it by putting an onClick
event handler on the component and toggling the state manually, but that is silly. Anyone have a clue?
The API is at https://material-ui.com/api/checkbox/#checkbox. Not rocket science.
In many cases, Material UI Checkbox onChange event is not working.
I suggest to save your time and use onClick event instead.
It will work always. Checkbox usually have a boolean value.
<Checkbox
checked={this.state.isTrue}
onClick={() => this.setState({isTrue: !this.state.isTrue})}
/>
The issue might come from the structure of your component as provided code is perfectly fine, here is a working exemple you can try on codesandbox.io.
Compare with your code and try to find differences, but isolating a specific element might be a good way to realise the issue might come from somewhere else.
import React, { Component } from "react";
import { render } from "react-dom";
import Checkbox from "material-ui/Checkbox";
class App extends Component {
constructor() {
super();
this.state = {
isTrue: false
};
}
render() {
return (
<div>
<Checkbox
checked={this.state.isTrue}
onChange={e => {
console.log(e.target.checked);
this.setState({ isTrue: e.target.checked });
}}
/>
</div>
);
}
}
render(<App />, document.getElementById("root"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With