Home > Mobile >  How to checked/uncheck all checkbox in react js?
How to checked/uncheck all checkbox in react js?

Time:08-02

  1. I want when I checked the child checkbox all the column checkbox should be checked in a row will be check
  2. I want if I checked the parent one all the table checkboxes should be check how i implement I need code example if you have Note: I am using functional react component with my custom table created by own not any table library. Thanks every one ! Custom table

CodePudding user response:

You can do it by this way

Here I am assuming that the data will be in following way:

permissons = [
              {create:false, read:false, edit: true, delete:true}
              {create:false, read: true, edit: false, delete:true}
             ]

const checkAll = (event, index) => {
const { checked } = event.target;
const newPermission = [...permissions];
if (checked === true) {
  // console.log("Checked");
  newPermission[index].create = true;
  newPermission[index].read = true;
  newPermission[index].edit = true;
  newPermission[index].delete = true;
} else if (checked === false) {
  // console.log("Unchecked");
  newPermission[index].create = false;
  newPermission[index].read = false;
  newPermission[index].edit = false;
  newPermission[index].delete = false;
}
setpermissions([...newPermission]);
};

Pass event and index as props in checkAll function.

CodePudding user response:

You need to create a pattern for row and column For instance For every row add index of row to each checkbox class like checkbox_${index}

Use queryselectorAll to target them and just trigger click

document.querySelectorAll(`row_${index}`).forEach(el=>el.click())

Similar the case for all checkbox in a column.

  • Related