Skip to content Skip to sidebar Skip to footer

Checkbox Not Toggling In React With Material-ui

So I have a React code in which the checkbox is not toggling when I click on it. This is the codesandbox link: https://codesandbox.io/s/inspiring-kirch-q6p4h I am initializing the

Solution 1:

I dug in on this a bit and after converting handleChange to use a functional state update

consthandleChange = (name, campid) => {
  setCheckBox((checkbox) => ({
    ...checkbox,
    [campid]: !checkbox[campid]
  }));
};

to try and avoid any stale enclosures with the columns prop passed to ThanosTable I dug in on that component code to see if/how it handled re-enclosed checkbox values passed in the columns prop.

Issue

The columns are stored in local state in the visibleColumns state and never again does ThanosTable look at and respond to changes on the columns prop.

Solution

Add an useEffect to update the visibleColumns state when props update.

useEffect(() => {
  setVisibleColumns(
    !options.removeColumnsFeature &&
    options.showColumns &&
    options.showColumns.length
    ? [...columns.filter((x) => options.showColumns.includes(x.key))]
    : [...columns]
  )
}, [columns, options]);

Edit checkbox-not-toggling-in-react-with-material-ui

You can, and should, factor the common logic between the visibleColumns state initializer and effect callback.

Solution 2:

Don't use the callback inside the useState declaration

Example Codesanbox

const [checkbox, setCheckBox] = useState({});

Post a Comment for "Checkbox Not Toggling In React With Material-ui"