TLDR: Use defaultChecked instead of checked, working jsbin.
Trying to setup a simple checkbox that will cross out its label text when it is checked. For some reason
onChange will not call handleChange on mobile when using defaultChecked. As an alternative you can can use onClick and onTouchEnd.
<input onClick={this.handleChange} onTouchEnd={this.handleChange} type="checkbox" defaultChecked={!!this.state.complete} />;
If you have a handleChange
function that looks like this:
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
});
}
You can create a custom onChange
function so that it acts like an text input would:
<input
type="checkbox"
name="check"
checked={this.state.check}
onChange={(e) => {
this.handleChange({
target: {
name: e.target.name,
value: e.target.checked,
},
});
}}
/>
To get the checked state of your checkbox the path would be:
this.refs.complete.state.checked
The alternative is to get it from the event passed into the handleChange
method:
event.target.checked
In material ui, state of checkbox can be fetched as
this.refs.complete.state.switched
It's better not to use refs in such cases. Use:
<input
type="checkbox"
checked={this.state.active}
onClick={this.handleClick}
/>
There are some options:
checked
vs defaultChecked
The former would respond to both state changes and clicks. The latter would ignore state changes.
onClick
vs onChange
The former would always trigger on clicks.
The latter would not trigger on clicks if checked
attribute is present on input
element.
In case someone is looking for a universal event handler the following code can be used more or less (assuming that name property is set for every input):
this.handleInputChange = (e) => {
item[e.target.name] = e.target.type === "checkbox" ? e.target.checked : e.target.value;
}