score:39

Accepted 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 || "" };

score:0

In my case, I was using a prop from my redux store to set whether the checkbox was checked, simply defaulting the property to false worked for me.

e.g.

const MyComponent = ({
  somePropFromRedux
}) => {
  return <thatThridPartyCheckboxComponent checked={somePropFromRedux} />
}

becomes (only change is adding = false on Line 2)

const MyComponent = ({
  somePropFromRedux = false
}) => {
  return <thatThridPartyCheckboxComponent checked={somePropFromRedux} />
}

score:0

do not use e.target.checked in the inputbox onChange eventHandler method.

Correct way:

  const [isChecked, setCheck] = useState(false);
 const handler = (e) => {
    setCheck(!isChecked);
  };

 <input
        type="checkbox"
        checked={isChecked}
        onChange={handler}
      />

score:1

Another simple way to do this would be to !! your props.checkboxValue value. That way even if it's undefined, !!props.checkboxValue will resolve to false.

this.state = { checkboxValue: !!props.checkboxValue };

score:2

Something worth noting about the above code snippet. When you set a state in the constructor from props, it is always best to set the state to a "controlled" value i.e. a tangible value such as an int, float, string, array, map, etc. The error you are getting is the result of props.value being set to null

So, Consider setting your constructor state like this:

this.state = {
    value: props.value ? props.value : 'empty'
}

What is happening here is it is checking if props.value has a value, if it does it sets the state to props.value, if props.value is null, it sets the state to the string: `'empty'

score:7

If you are using a checkbox react won't like a string either so instead try

this.state = { checkboxValue: props.checkboxValue || false };

Related Query

More Query from same tag