Checkbox state not toggle. Material UI React

Viewed 14629

I use Material UI checkbox component, and try toggle state onCheck, in console state changes but in UI not, the check mark does not toggle. what did I mess.

class CheckboxInteractivity extends React.Component {

    state = {
        switched: false,
    }

    componentWillMount() {
        const {checked} = this.props
        if (checked) {
            this.setState({
                switched: true,
            })
        }
    }

    handleChange = (event, switched) => {
        this.setState({switched: !this.state.switched})
    }

    render () {
        const {switched} = this.state

        return <Checkbox
            label="Label"
            checked={switched}
            onCheck={this.handleChange}
            {...this.props}
                />
    }
}

CheckboxInteractivity.propTypes = {
    checked: PropTypes.bool,
}

export default CheckboxInteractivity

components

<CheckboxInteractivity /> 
//working correctly
<CheckboxInteractivity checked/>
//not working 
2 Answers

I ran into this problem when using two Mui Checkboxes which values depends on each other.

I had "parent state" which I tried to use within both of the checkboxes. I provided this state using context provider.

Solution

I solved the problem by initializing separate state const [checked, setChecked] = useState(false) inside both of the checkbox components. I did this to prevent "uncontrolled" component initialization.

To bind "checked" states to parent state, I defined a simple useEffect() function.

Like this:

export const DrugUsageStartCheckBox = () => {
    const { t } = useTranslation();
    // parent state can be used only if component is wrapped to context provider.
    const {state, dispatch} = useParentState();
    const [checked, setChecked] = useState(false)

    useEffect(() => {
        setChecked(state.checked)
    }, [state.checked])

    return (
            <Checkbox
                id={'my-checkbox'}
                checked={checked}
                onChange={(e) => {
                    dispatch({type: "toggleChecked"})
                }}
    ...

Related