Search code examples
javascriptreactjsmaterial-uimaterial-table

access clicking edit icon in material table


enter image description here

I am using Material Table in Reactjs to show the table Data. Here I am stuck at a part where I want to change state when I click on the edit option/icon. I do not want to change the onClick functionality of Edit button, but I just want to access edit icon. Is there any way I can achieve it?

Note: I only want it when I click on the edit(pen) icon before it becomes the OK and Cancel buttons. enter image description here


Solution

  • First of all you have to remove the default edit button. Then use a Button in action and tableRef props. Now, all you have to do is put the edit's code in onClick event like this:

    var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
    var _objectSpread2 = _interopRequireDefault(
      require("@babel/runtime/helpers/objectSpread")
    );
    ...
    
    export default function MaterialTableDemo() {
      const tableRef = useRef(null);
      ...
      return (
        <MaterialTable
          ...
          tableRef={tableRef}
          actions={[
            {
              onClick: (event, rowData) => {
                console.log("Clicked", rowData);
                tableRef.current.dataManager.changeRowEditing(rowData, "update");
    
                tableRef.current.setState(
                  (0, _objectSpread2["default"])(
                    {},
                    tableRef.current.dataManager.getRenderState(),
                    {
                      showAddRow: false,
                    }
                  )
                );
              },
            },
          ]}
          ...
        />
      )
    }
    

    This part is the requirements that material-table uses in it's code:

    var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
    var _objectSpread2 = _interopRequireDefault(
      require("@babel/runtime/helpers/objectSpread")
    );
    

    In addition this is the code that you need to fire edit action:

    tableRef.current.dataManager.changeRowEditing(rowData, "update");
    tableRef.current.setState(
      (0, _objectSpread2["default"])(
        {},
        tableRef.current.dataManager.getRenderState(),
        {
          showAddRow: false,
        }
      )