Hello how can I handle onChange for multiple check box? The following example allows me to control the value of one checkbox.
class App extends Component {
constructor() {
super();
this.state = {
i_agree: false
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({i_agree: !this.state.i_agree});
}
handleSubmit(event) {
console.log(this.state);
event.preventDefault();
}
render() {
return (
<div>
<h1>React Checkbox onChange Example - ItSolutionStuff.com</h1>
<form onSubmit={this.handleSubmit}>
<label>
<input
type="checkbox"
defaultChecked={this.state.i_agree}
onChange={this.handleChange}
/> I Agree with this content...
</label>
<label>
<input
type="checkbox"
defaultChecked={this.state.isChecked}
onChange={this.handleChange}
/> I want to control this...
</label>
<input type="submit" value="Submit" />
</form>
</div>
);
}
}
How can I set my handleChange function to handle changes for each checkbox instead of checking for one.
Attempt 1
class App extends Component {
constructor() {
super();
this.state = {
i_agree: false,
isChecked: false
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({
[e.target.name]: !e.target.value
});
}
handleSubmit(event) {
console.log(this.state);
event.preventDefault();
}
render() {
return (
<div>
<h1>React Checkbox onChange Example - ItSolutionStuff.com</h1>
<form onSubmit={this.handleSubmit}>
<label>
<input
type="checkbox"
defaultChecked={this.state.i_agree}
onChange={this.handleChange}
name="i_agree"
/> I Agree with this content...
</label>
<label>
<input
type="checkbox"
defaultChecked={this.state.isChecked}
onChange={this.handleChange}
name="isChecked"
/> I want to control this...
</label>
<input type="submit" value="Submit" />
</form>
</div>
);
}
}
I Updated the onChange handler and added name attributes in each label. But this did not work or threw any errors.