Reputation: 116
I am working on a checkbox and a textfield in React Js. Textfield works fine but my checkbox does not change its state from the one assigned in the constructor. I am not able to find any mistake in my method "handleChange". Kindly help
My component is
import React from "react"
class App extends React.Component {
constructor() {
super()
this.state = {
name: "",
work1: false
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(event) {
const {name, value, type, checked} = event.target
type === "checkbox" ? this.setState({[name]: checked}) : this.setState({[name]: value})
}
render() {
return (
<div className="todo-item">
<input
type="checkbox"
onChange = {this.handleChange}
checked={this.state.work1}
/>
<input
type = "text"
name= "name"
value= {this.state.name}
onChange={this.handleChange }
/>
<p >{this.state.name}</p>
</div>
)
}
}
export default App
Upvotes: 0
Views: 126
Reputation: 410
You have not give the checkbox field name property like below
<input
type="checkbox"
name="work1"
onChange = {this.handleChange}
checked={this.state.work1}
/>
Upvotes: 5