lundi 30 septembre 2019

How to make enabling a button work when any of checkboxes is selected with react hooks?

I have a bug in enabling a button, when any of the checkboxes is selected. Currently it doesnt work on the first click, but only on the second one. Unselecting a checkbox works on the first click also. I think it has something to do with states, but I don't really understand what is causing the problem.

I tried commenting out this line: checked.length > 0 ? setTaskBtnsEnabled(true) : setTaskBtnsEnabled(false); and it removes the issue so I'm sure it has something to do with the useState. However that line is vital for me so I should come up with a fix for this. I also tried to start with opposite boolean values and the issue remains.

Upper component:

const checkedBoxes = () => {
    var checkedOnes = [];
    for (
      var i = 0;
      i < document.getElementsByClassName('count-checkboxes').length;
      i++
    ) {
      if (document.getElementsByClassName('count-checkboxes')[i].checked) {
        checkedOnes.push(
          document.getElementsByClassName('count-checkboxes')[i].parentNode
            .id
        );
      }
    }
    return checkedOnes;
  };

  const [taskBtnsEnabled, setTaskBtnsEnabled] = useState(false);
  const handleBtnsEnabling = event => {
    var checked = checkedBoxes();
    checked.length > 0 ? setTaskBtnsEnabled(true) : setTaskBtnsEnabled(false);
  };

Component inside the previous one:

<Button
   disabled={!taskBtnsEnabled}
   id="nappi"
>
   OK
</Button>

The issue is that first click doesn't work and it doesn't check the checkbox. No error messages coming to console.




Aucun commentaire:

Enregistrer un commentaire