mercredi 13 mai 2020

In React how do I handle 100 checkboxes in React-Table and get their value

I have a react-table where I'm generating about 100 checkboxes dynamically. I have tried everything I can think of, but checking/unchecking the checkboxes takes a very long time before I can see any changes. It seems to be re-rendering every single checkbox before I can see a tick on the checkbox I just clicked on (the page freezes for about 5-10 secs). I'm using a change handler defined in a wrapper component passing as a prop.

// Generate columns for table
// this is added to the column props of React-Table
function setActionsColumns() {
  return rolesActionsList.map((action, index) => {
    const actionName = get(action, 'name');

    return {
      Header: actionName,
      accessor: actionName,
      Cell: row => {
        const objectName = get(row, 'original.name');
        let data = formData.permissions.filter(
          perm => row.tdProps.rest.action === perm.action
        );

        let roleData = data[0];
        let checked;

        if (get(roleData, 'object') === row.tdProps.rest.object) {
          checked = get(roleData, 'checked');
        }

        return (
          <Checkbox
            key={`${actionName}_${index}`}
            name={actionName}
            onChange={onCheckboxChange}
            data-object={objectName}
            checked={checked}
          />
        );
      },
    };
  });
}


// Checkbox handler defined in a class component
handleCheckboxChange = (event: SyntheticEvent<HTMLInputElement>) => {
  const { roleData } = this.state;
  const target = event.currentTarget;
  const actionName = target.name;
  const checked = target.checked;
  const objectName = target.dataset.object.toUpperCase();
  const checkedItem = {
    action: actionName,
    object: objectName,
    checked,
  };
  let checkedItemsList = [];
  let isInArray = roleData.permissions.some(perm => {
    return perm.action && perm.object === checkedItem.object;
  });

  if (!isInArray) {
    checkedItemsList = [...roleData.permissions, checkedItem];
  } else {
    checkedItemsList = roleData.permissions.filter(
      perm => perm.action !== checkedItem.action
    );
  }

  this.setState({
    roleData: {
      ...this.state.roleData,
      permissions: checkedItemsList,
    },
  });
};



Aucun commentaire:

Enregistrer un commentaire