jeudi 5 décembre 2019

Unable to check and uncheck checkbox in reactjs

When i choose check in checkbox the value should be inserted in hobby array and when i unchecked the value should be removed from array value is inserting and removing from array but i am not able to check and unchecked the checkbox visually. but in state it's working.

 const ContactForm = () => {
 const [state,setContact] = useState({
        userId:"",
        firstName:"",
        lastName:"",
        jobTitleName:"",
        employeeCode:"",
        emailAddress:"",
        phoneNumber:"",
        country:"",
        status:"active",
        hobbies:[]
 })   
 const onChange = (event)=>{   
    setContact({...state,[event.target.name]: event.target.value}); 
 }
 e.preventDefault();
}
return (
   <div className="form-group mb-2">
    <label className="mb-0 font-weight-bold">Hobbies</label>
    <div className="form-check">
    <input type="checkbox" value="Basketball"   onChange={(e)=>{
       if(e.target.checked)

       {
        state.hobbies.push(e.target.value)
        console.log(state.hobbies)
    }else { 
        var index = state.hobbies.indexOf(e.target.value);
        if (index > -1) {
            state.hobbies.splice(index, 1);
            console.log(state.hobbies)
   }
   }
    }
    }
   />

  <label className="form-check-label">
   Basketball
  </label>
</div>
<div className="form-check">
<input type="checkbox" value="Vollyball"   onChange={(e)=>{
       if(e.target.checked)
       {
        state.hobbies.push(e.target.value)
        console.log(state.hobbies)
    }else { 
        var index = state.hobbies.indexOf(e.target.value);
        if (index > -1) {
            state.hobbies.splice(index, 1);
            console.log(state.hobbies)

}
       }
           }
           }
       />

Vollyball )




Aucun commentaire:

Enregistrer un commentaire