Reputation: 522
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.
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}
/>
))}
</>
);
}
Upvotes: 0
Views: 38
Reputation: 8774
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}
/>
))}
</>
);
}
Upvotes: 2