0
votes

I create a material-table in react and I want to use the checkbox in it. How can I do that?

enter image description here

1

1 Answers

1
votes

I made this example following the official docs:

checkbox_field_demo

To make it work you need to specify editComponent and render attributes on the column definition:

{
  title: "booleanValue",
  field: "booleanValue",
  editComponent: (props) => {
    return (
      <input
        type="checkbox"
        checked={props.value}
        onChange={(e) => props.onChange(e.target.checked)}
      />
    );
  },
  render: (rowdata) => (
    <input type="checkbox" checked={rowdata.booleanValue} />
  )
}

Also you have to define onRowAdd, onRowUpdate and onRowDelete functions as part of the editable prop:

 editable={{
      onRowAdd: (newData) =>
        new Promise((resolve, reject) => {
          setTimeout(() => {
            setData([...data, newData]);

            resolve();
          }, 1000);
        }),
      onRowUpdate: (newData, oldData) =>
        new Promise((resolve, reject) => {
          setTimeout(() => {
            console.log(oldData);
            const dataUpdate = [...data];
            const index = oldData.tableData.id;
            dataUpdate[index] = newData;
            setData([...dataUpdate]);

            resolve();
          }, 1000);
        }),
      onRowDelete: (oldData) =>
        new Promise((resolve, reject) => {
          setTimeout(() => {
            const dataDelete = [...data];
            const index = oldData.tableData.id;
            dataDelete.splice(index, 1);
            setData([...dataDelete]);

            resolve();
          }, 1000);
        })
    }}

Here is the link to the working sandbox! Good luck!