samedi 18 décembre 2021

React mui 5 checkbox don't change value under function

When Checkbox is under a FormControlLabel and function, the value don't change when useState change another variable.

If I comment the useState, checkbox works.

If I move the same code (checkbox and formcontrolLabel) on a render, not in function, checkbox work.

The sample code :

import * as React from "react";
import {
  Theme,
  useTheme,
  Box,
  Stack,
  Checkbox,
  FormControlLabel,
} from "@mui/material";

export const RunnerRaces2: React.FC<{}> = (props) => {
  const theme = useTheme();
  const [dataSource, setDataSource] = React.useState<[]>(
  );
  const FrmCheckBox: React.FC<{ label: string }> = (props) => {
    const [checked, setChecked] = React.useState(true);
    return (<FormControlLabel
      label={props.label}
      control={
        <Checkbox
          // checked={checked}
          // defaultChecked
          size="small"
          onChange={(
            event: React.ChangeEvent<HTMLInputElement>
          ) => {
            const value = event.target.checked;
            setDataSource([]);
          }}
        />
      }
    />);
  };

  return (
    <Box>
      <Stack
        direction="row"
      >
        <FrmCheckBox
          label={"t1"} />
        <FrmCheckBox
          label={"t2"} />
        <FrmCheckBox
          label={"t3"} />
        <FrmCheckBox
          label={"t4"} />
      </Stack>
    </Box>
  );
};

I don't understand, it's mui 5 bug ? react bug ? or a wrong code from me ?

sample on codesandbox.io




Aucun commentaire:

Enregistrer un commentaire