Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A component is changing an uncontrolled input of type checkbox to be controlled in React JS

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.

My Code:

      interface IState {
      isSelectedAll: boolean;
      selected: any;
      confirmDelete: boolean;
      confirmSignStatus: boolean;
      petitionId: any;
      items: any;
      verificationCode: any;
    }
...
    /**
     * Default state.
     */
    function getDefaultState(): IState {
      return {
        isSelectedAll: false,
        selected: {},
        confirmDelete: false,
        confirmSignStatus: false,
        petitionId: '',
        items: [],
        verificationCode: null,
      };
    }

  public handleSelect = (id: number) => {
    let selectedObj = Object.assign({}, this.state.selected);
    selectedObj[id] = !selectedObj[id];
    this.setState({ selected: selectedObj });
  }
...

  public state: IState = getDefaultState();


 public componentWillReceiveProps(nextProps: any): void {
    if (nextProps.ecourtListBranch.data) {
      this.initSelects(nextProps.ecourtListBranch.data);
    }
  }

      private initSelects = (data: any): void => {
        let selectedObj: any = {};
        data.map((item: IPetitionView) => {
          selectedObj[item.petitionId] = false;
          this.setState({ selected: selectedObj });
        });
      }

interface IProps {
  ecourt: IPetitionView;

  ecourtActions: typeof EcourtActions;

  handleSelect: (id: number) => any;

  selecteds: any;

  handleDeletePetition: (petitionId: number) => any;

  handleEditPetition: (petitionId: number) => any;
}

...

<Checkbox
  value={this.props.selecteds[petitionId]}
  onChange={() => handleSelect(petitionId)}
 />
like image 530
Leyli Abbasova Avatar asked Jan 25 '19 11:01

Leyli Abbasova


1 Answers

It means that this.props.selecteds[petitionId] is undefined at times. One thing you could do is give a default value to the checkbox like so.

<Checkbox
  value={this.props.selecteds[petitionId] || false}
  onChange={() => handleSelect(petitionId)}
 />

Warning note: don't use the defaultValue prop because it makes your component uncontrolled by definition.

like image 54
Nielsvandenbroeck Avatar answered Oct 06 '22 15:10

Nielsvandenbroeck