Search code examples
javascriptreactjscheckboxmaterial-uicheckboxlist

React Dynamic Checkbox list doesn't marked when i checked


Please help with this matter: I'm making a nested dynamic list of checkboxes to select companies and groups of this companies, investigating, i have the following result

  const [checkedGroups, setCheckedGroups] = useState([]);
  const handleChangeGroup = (event) => {
    const index = checkedGroups.indexOf(event.target.value);
    if (index === -1) {
      setCheckedGroups([...checkedGroups, event.target.value]);
    } else {
      setCheckedGroups(checkedGroups.filter((checkedGroup) => checkedGroup !== event.target.value));
    }
    console.log(checkedGroups,index,event.target.value,checkedGroups.includes(event.target.value));

  };
inside jsx ...

  <Grid item xs={12} md={12}>
    <Typography variant="h6">Empresas Activas </Typography>
    <Box>
      {companiesList.map((company) => (
        <Box key={company.id}>
          <FormControlLabel key={company.id} control={<Checkbox />} label={company.name} />
          {company.groups.map((group) => (
            <Box key={group.id} sx={{ display: 'flex', flexDirection: 'column', ml: 3 }}>
              <FormControlLabel control={<Checkbox checked={checkedGroups.includes(group.id)} value={group.id} onChange={handleChangeGroup} />} label={group.name} />
              {checkedGroups.includes(group.id)}
            </Box>
          ))}
        </Box>
      ))}
    </Box>
  </Grid>

Almost result checkbox list:

The checkoxes list displays as espected even the handling checks for groups, displays accurate data for procesesing and no errors in anytime, but the big problem is: the checkboxes doesn't change to checked or unchecked in any time, what i'm doing wrong?

As you can see the checked prop in the checbox components is determined by checked={checkedGroups.includes(group.id)} and when in check in console this value show true or false, at the moment the checked element is incorporated or eliminated front the list


Solution

  • Take a look at this api for checkbox in MUI doc. Here focus on the last property value it is saying that "The DOM API casts this to a string." this means whatever you pass as value to value it will convert it as a string.

    So for your example you are doing value={group.id}. Here my guess is that group.id is a number value. And as you are passing it to the Checkbox it becomes string. And now you are checking checked={checkedGroups.includes(group.id)} but here it is checking the value against number verson of the same value.

    So for instance if your checkedGroups becomes ['1', '2'] even you passed 1 and 2 as number. You are just making the comparison like is '1' === 1 and its false as it's checking value as well as type.

    So the answer to your questions is that where you are doing checked={checkedGroups.includes(group.id)} replace it with checked={checkedGroups.includes(group.id.toString())}