3

Having the following React Component for Custom Checkbox where values are passed down as props from parent

export const CheckBox = (props) => {
  let closeClass;

  if (!props.hint && props.hint == "") {
    closeClass = "no-hint";
  }
  return (
    <div className={"field-wrapper checkbox-button-grouped"}>
      <label htmlFor={`checkbox_${props.value}`}>
        <input
          onChange={props.handleCheckChieldElement}
          type="checkbox"
          name={props.name}
          id={`checkbox_${props.value}`}
          className={"input-field"}
          checked={props.isChecked}
          value={props.value || ""}
        />
        <div className="label-text">
          <div className={"label-name"}>{props.label}</div>
          {props.hint && props.hint !== "" ? (
            <div className={"info-icon"}>
              <InfoIcon className={"info-icon"} />
            </div>
          ) : null}
          <div className={"hint"}>{props.hint}</div>
          <UncheckIcon className={classnames("uncheck", closeClass)} />
          <Checkmark className={"ok-icon"} />
        </div>
      </label>
    </div>
  );
};

export default CheckBox;

I keep getting the following error

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). Decide between using a controlled or uncontrolled input element for the lifetime of the component.

What I'm doing wrong in this case?

1
  • 2
    You can try: checked={Boolean(props.isChecked)} Commented May 6, 2020 at 15:33

2 Answers 2

6

props.isChecked is probably null or undefined, you can solve it like this:

checked={props.isChecked || false}
Sign up to request clarification or add additional context in comments.

Comments

0

Warning: A component is changing an uncontrolled input of type checkbox to be controlled

If you are getting this error, it means that the value you are providing to the input field is not updated by your onChange function.

The value state that is assigned to any input should be only modified through the onChange function else you get this warning.

It is also possible that the value is undefined as soon as the onChange action is performed.

As of your case declare

isChecked as a boolean with initial value as false or true as you like.

If you are using hook

const [isChecked, setIsChecked] = React.useState(false);

for class component

this.state = {
   isChecked: false
}

Here is the working code in code sandbox code

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.