reactjstypescriptmaterial-ui

React Material UI Checkbox how to change checked


I have many checkboxes, and use them to set table columns.
It's look like

const [fields, setFields] = useState<Set<string>>(new Set(["name"]));

const handleChangeFilter = (event: ChangeEvent<HTMLInputElement>) => {
    if (fields.has(event.target.value)) {
        fields.delete(event.target.value)
    } else {
        fields.add(event.target.value)
    }
    setFields(fields)
};
{filters.map((field) => {
    return (<FormControlLabel control={<Checkbox onChange={(event) => {
handleChangeFilter(event) }} value={field} checked={fields.has(field)} />} label={ field } />)   
})}

and fields changes as expected but checkboxs doesn't work.

I click and field add in fields but checkbox dosn't change.

Am I need state control for every field, but there're to many. I don't try to use Map in useState is it good idea?


Solution

  • The issue with your checkbox not updating is that Set is a mutable object, and React doesn't detect changes in its state when you modify it directly. To solve this, you should create a new Set and update the state with this new Set.

    const [fields, setFields] = useState<Set<string>>(new Set(["name"]));
    
    const handleChangeFilter = (event: ChangeEvent<HTMLInputElement>) => {
        const newFields = new Set(fields);
        if (newFields.has(event.target.value)) {
          newFields.delete(event.target.value);
        } else {
          newFields.add(event.target.value);
        }
        setFields(newFields);
    };