samedi 29 août 2020

React - what is the best way to set for checkbox checked field

In below code, I use a function this.isExist(data.id, "") to evaluate the checked value.
But sometimes click the checkbox of the item, it does not change from empty to ticked,
meanwhile the selected array does add the item.
Is it related to the checked prop of input?

state= {
  selected: [],
}
isExist = (id, group) => {
if(!this.props.selected){
  console.log("selected = null")
  return null;
}
// return this.props.selected.find(ele => ele.id == group + id);

return this.props.selected.some(item=> item.id == group + id);
};

return 
<div style=>
                      {this.state.groupMembersList[groupData.id] && this.state.groupMembersList[groupData.id].length > 0 ?
                        this.state.groupMembersList[groupData.id].map(data => (
                        <div key={data.id} className="popup-contact__item">
                          <label>
                            <input
                              id={data.id}
                              key={data.id}
                              className="checkbox"
                              type="checkbox"
                              group= {groupData.id}
                              onChange={async(e) => {await onSelect(e); await this.checkIfAllSelected();}}
            
                              name={(data.firstName&&data.lastName?(data.firstName + " " + data.lastName):data.firstName)+" ("+t("mobile") + ": " + (!data.mobileCountryCode || data.mobileCountryCode === "+852"?"":data.mobileCountryCode) +
                              data.mobileNumber+")"}
                              checked={this.isExist(data.id, "")}
                              disabled={ this.state.groupLoading }
                            />
                            {data.firstName&&data.lastName?(data.firstName + " " + data.lastName):data.firstName } ({t("mobile") + ": " + (!data.mobileCountryCode || data.mobileCountryCode === "+852"?"":data.mobileCountryCode) +
                            data.mobileNumber+")"}
                          </label>
                        </div>



Aucun commentaire:

Enregistrer un commentaire