0

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
4
  • 3
    It doesnt have a name Commented Feb 7, 2020 at 14:22
  • It worked but as i am a beginner in React can u tell why is it important to use name Commented Feb 7, 2020 at 14:24
  • Because you're using the name to set the state. this.setState({[name]: checked}) Commented Feb 7, 2020 at 14:24
  • because you make use of if :D this.setState({[**name**]: checked}) Commented Feb 7, 2020 at 14:25

1 Answer 1

5

You have not give the checkbox field name property like below

<input 
  type="checkbox"
  name="work1"
  onChange = {this.handleChange}  
  checked={this.state.work1}   
/>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.