mardi 18 juin 2019

React - dynamically create select all checkboxes

There has been a number of questions on React checkboxes. This answer is pretty good, and it helps to modularize the idea of select-all checkboxes in React.

Now, I have a problem. I have a dictionary like this:

{
  regionOne: {
    subareaOne,
    subareaTwo,
    subareaThree,
    subareaFour
  },
  regionTwo: {
    subareaFive,
    subareaSix
  }
}

Here, each region is mapped to an arbitrary number of sub areas, which I do not know beforehand.

I want to create checkboxes such that each region and each subarea has a checkbox, and each region's checkbox acts as a select-all/de-select all for all the subareas it is mapped to. That is, something like this:

enter image description here

enter image description here

So, when you click on the checkbox for regionOne, the checkboxes for subareaOne, subareaTwo, subareaThree and subareaFour should all be checked as well, but not those in regionTwo.

I think I can adapt this answer, but its getInitialState function assumes that you know how many children checkboxes there are.

Any idea on how to do this in an elegant method? I am now considering initialising the checkboxes dynamically using mapping, but I am not sure...VanillaJS would have been much simpler >.<




Aucun commentaire:

Enregistrer un commentaire