Javascript – React a component is changing an uncontrolled input of type checkbox to be controlled

javascriptreactjs

react gives me a warning: "A component is changing an uncontrolled input of type checkbox to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa)."

However my checbox is change via the state property. Am I missing something obvious?

    import React from 'react';

// Components
import Checkbox from './checkbox';
import HelpBubble from './helpBubble';

export default class CheckboxField extends React.Component {


    constructor(props) {
        super(props);
        this.state = {value: props.value};
        this.handleChange = this.handleChange.bind(this);
    }

    handleChange(event) {
        this.setState({value: event.target.value});
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.value !== this.props.value) {
            this.setState({value: nextProps.value});
        }
    }

    render() {
        const {label, meta = {}, help, disabled, required, onChange} = this.props;

        return (
            <label className="checkbox-wrap form-field">
                <Checkbox
                    disabled={disabled}
                    type="checkbox"
                    onChange={(event) => {
                        onChange(event, !this.state.value);
                    }}
                    checked={this.state.value}/>
                {label && (
                    <div className="checkbox-label">
                        {label}
                        {required && <div className="form-field__required"/>}
                    </div>
                )}
                {help && <HelpBubble help={help}/>}
                {meta.error && meta.touched && (
                    <div className="input-error">{meta.error}</div>
                )}
            </label>
        );
    }}

Parent component:

handleChangeParams(key, value)
}
/>
Handle change params changes the value in model and calls server. Depending on server result, the value can change.

Thanks in advance.

Best Answer

If your state is initialized with props.value being null React will consider your Checkbox component to be uncontrolled.

Try setting your initial state so that value is never null.

this.state = { value: props.value || "" };