MUI: Keep track of multiple Checkbox states

Viewed 1144

I have a checkbox element within a tab using MUI. When switching tabs it removes the checkbox visual.

{listItem.map((checkbox, index) => {
          return (
            <FormControlLabel className="twocolelement"
        control={
          <Checkbox
          key={(index) + (checkbox.Name)}
            name={checkbox.Name}
            value={checkbox.Weight}
            id={checkbox.Category}
            checked={isChecked==index}
            color="primary"
            onChange={event => handleCheckboxChange(index, event)}
            onClick={() => isCheckboxChecked(index)}
          />
        }
        label={(checkbox.Brand) + ' ' + (checkbox.Name)}
      />

          );
        })}
  const [isChecked, setIsChecked] = React.useState([]);

  const isCheckboxChecked = (index) => {
    setIsChecked(index)
    console.log(index)
}

This keeps the state but it works like a radio button (only allowing one selection)

How do I keep the checkbox state (checked) when moving between tabs?

1 Answers

If you want to store all of the Checkboxs state:

const [isChecked, setIsChecked] = React.useState(() =>
  listItem.map((i) => false)
);

const isCheckboxChecked = (index, checked) => {
  setIsChecked((isChecked) => {
    return isChecked.map((c, i) => {
      if (i === index) return checked;
      return c;
    });
  });
};
console.log(isChecked);

return (
  <div>
    {listItem.map((checkbox, index) => {
      return (
        <FormControlLabel
          key={index + checkbox.name}
          className="twocolelement"
          control={
            <Checkbox
              name={checkbox.name}
              value={checkbox.weight}
              id={checkbox.category}
              checked={isChecked[index]}
              color="primary"
              onChange={(e) => isCheckboxChecked(index, e.target.checked)}
            />
          }
          label={checkbox.name}
        />
      );
    })}
  </div>
);

Codesandbox Demo

Related