React state conflict with javascript "document.getElementById" function

73 views Asked by At

I have this function in my React web application:

const handleRateLightSelection = (cardId, rateId) => {

setRateLightSelected(0);

if (lastSelectedLightCardId != -1 && lastSelectedLightCardId != cardId) {

  document.getElementById('lightBox-' + lastSelectedLightCardId).classList.remove("rate-box-grosso-light");
  document.getElementById('lightBox-' + lastSelectedLightCardId + '-check').classList.add("d-none");

}

if (lastSelectedLightCardId == -1 || lastSelectedLightCardId != cardId) {

  document.getElementById('lightBox-' + cardId).classList.add("rate-box-grosso-light");
  document.getElementById('lightBox-' + cardId + '-check').classList.remove("d-none");

  setRateLightSelected(rateId);

} else {

  var boxSelection = document.getElementById('lightBox-' + cardId).classList.contains("rate-box-grosso-light");

  if (boxSelection) {

    document.getElementById('lightBox-' + cardId).classList.remove("rate-box-grosso-light");
    document.getElementById('lightBox-' + cardId + '-check').classList.add("d-none");

    setRateLightSelected(0);

  } else {

    document.getElementById('lightBox-' + cardId).classList.add("rate-box-grosso-light");
    document.getElementById('lightBox-' + cardId + '-check').classList.remove("d-none");

    setRateLightSelected(rateId);

  }

}

lastSelectedLightCardId = cardId;
}

Using document.getElementById function, I'm handling boxes styles when users select them. All is working fine by now.

In retrospect, I've added setRateLightSelected state to handle the selection ID save and send it to my backend in a later time. After I've added this, the document.getElementById functions stopped working and I don't understand why?

0

There are 0 answers