lundi 12 juillet 2021

Checkbox select all logic react js.How to unselect one by one afterwards?

As per title I am implementing a checkbox that select all checkboxes and it works but when I am unselecting one by one the check remains on the current row and vanish on the others.

NOTE ABOUT LOGIC: I have a separate component where I have my single checkbox to select all and with that checked I set a boolean variable in the localstorage to be read in another component.

principalCheckbox code:

  function handleChange() {
if(checked===false) { localStorage.setItem('selectAllChecked', String(true));  
 dispatch(reduxActions.selectAll());
setChecked(true);}

 else {
  dispatch(reduxActions.clearSelection()); 
  localStorage.setItem('selectAllChecked', String(false));
  setChecked(false)
  }
 }
 ...    


<input type="checkbox" checked={checked} onChange={handleChange} />

Single checkboxes logic

        <input
            
              type="checkbox"
              checked={checked ?checked : areAllSelected}
              onChange={handleChange}
              
            />
          </div>

Let us analyze that condition {checked ?checked : areAllSelected}:

case1:so checked initially is false(nothing is selected so it goes in the else->but are allselected is also false so initially nothing is selected->OK)

case2: i click on single checkboxes so checked exist and the value is that "checked" so the single item is correctly selected->ok

case3: I click on selectAll and previously there was nothing checked so the condition go to the else and are all selected -OK

case4: same of case 3 ,I select everything but then when I click on single row the value of selectAll is false and the one of the single row is true (but previously was also checked) and it remains checked while should be deselected

Any ideas on how to achieve that?




Aucun commentaire:

Enregistrer un commentaire