0

I'm using a material-ui checkbox that uses state. When I click to select an option, it selects all, but I would like him to select only the one that was clicked.

enter image description here

code:

export default function Categorys() {
  const [state, setState] = React.useState({
    checkedG: true
  });

  const handleChange = event => {
    setState({ ...state, [event.target.name]: event.target.checked });
  };
  return (
    <>
      {categorys.map(category => (
        <FormControlLabel
          key={category.id}
          control={
            <GreenCheckbox
              checked={state.checkedG}
              onChange={handleChange}
              name="checkedG"
              key={category.id}
            />
          }
          label={category.name}
        />
      ))}
    </>
  );
}

1 Answer 1

2

Because they all have the same checked attribute. Change it to:

export default function Categorys() {
  const [state, setState] = React.useState({});

  const handleChange = event => {
    setState(prevState => { ...prevState, [event.target.name]: event.target.checked });
  };
  return (
    <>
      {categorys.map(category => (
        <FormControlLabel
          key={category.id}
          control={
            <GreenCheckbox
              checked={state[category.id]}
              onChange={handleChange}
              name={category.id}
              key={category.id}
            />
          }
          label={category.name}
        />
      ))}
    </>
  );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.