handle checkbox to update its value in edit operation in functional component

Viewed 30

I am working on checkbox where if we checkbox is checked then a dropdown should be displayed. I have tried it but neither its value is not getting updated nor dropdown is shown/hidden when checkbox is checked/unchecked.

I have tried below:

const [recursive, setRecursive] = useState(false);
const [recursiveType, setRecursiveType] = useState("");
const [formState, setFormState] = useState({
    title: "",
    trainingDesc: "",
    category: "",
    trainingOn:"",
    recursive:false,
    recursiveType:""
});

const addTraining = (e) => {
    e.preventDefault();
    if (!editMode) {
        const trainingObj = {
            id: uuid(),
            title: formState.title,
            trainingDesc: formState.trainingDesc,
            category: formState.category,
            trainingOn: trainingDate,
            recursive: (formState.recursive) ? 1 : 0,
            recursiveType: recursiveType,
            dateTime: new Date().getTime()
        }
        dispatchRedux(createTraining(trainingObj));
    }
    else {
        dispatchRedux(updateTraining(formState, id));
    }
    navigate('/trainings');
}

Checkbox code:

<form onSubmit={addTraining}>
 --------------------
 --------------------
 <label htmlFor="recursive">Recursive</label> &nbsp;
 <input type="checkbox" name="recursive" id="recursive" checked={formState.recursive} onChange={()=>setRecursive(recursive=>!recursive)} />
{ (formState.recursive) && 

 <div className="col-4 form-group" style={{marginLeft:'-16px'}}>
   <label htmlFor="recursiveType">Recursive Type</label>
   <select name="recursiveType" onChange={(e)=>setRecursiveType(e.target.value)} value={formState.recursiveType} className="form-control" id="category" required>
      <option value="">Select</option>
      <option value="daily">Daily</option>
      <option value="weekly">Weekly</option>
      <option value="monthly">Monthly</option>
    </select>
 </div> }
</form>

My problem here is when I click on checkbox and then checkbox is checked/unchecked then dropdown is not getting shown/hidden. Any help would be appreciated.Thanks.

1 Answers

you need to change your code with this one :

  <input type="checkbox" name="recursive" id="recursive" checked={formState.recursive} 
   onClick={()=>setFormState({...formState, recursive:!formState.recursive})} />

{formState.recursive && <div className="col-4 form-group" style={{marginLeft:'-16px'}}>
   <label htmlFor="recursiveType">Recursive Type</label>
   <select name="recursiveType" onChange={(e)=>setRecursiveType(e.target.value)} value={formState.recursiveType} className="form-control" id="category" required>
      <option value="">Select</option>
      <option value="daily">Daily</option>
      <option value="weekly">Weekly</option>
      <option value="monthly">Monthly</option>
    </select>
 </div> } 

Works for me :)

Have a nice day!

Related