Check if a material-table row is still in edit mode
Asked Answered
T

2

7

I'm using the material-table in a material-ui Stepper and the user tends to click on "next" button even though the table is still in edit mode. This results in a loss of data.

Can I somehow access the table information to check if the table/row is still in edit mode when the user clicks the "next" button?

Talon answered 28/9, 2019 at 9:16 Comment(0)
J
6

While there's no directly exposed method that would tell you if the table is editable mode or not (and I think there should be), you can still find it out, but you will have to mess a bit with it's internals. First you will need to grab the ref of the table (find tableRef property) and then the property that will help you is lastEditingRow in the state of the table.

So, having tableRef that would be: tableRef.current.state.lastEditingRow. For a table in editing mode lastEditingRow will be set to an object describing the row being edited and undefined if table is not in editing mode.

CodeSandbox with example for you: https://codesandbox.io/s/fancy-waterfall-lg2ri

Jerryjerrybuild answered 28/9, 2019 at 10:57 Comment(2)
Thanks a lot for the hint about the tableRef prop. It perfectly works for me :) I think you should also test if tableRef.current.state.showAddRow is false. Otherwise, the user might create a new row, fills out all the details, clicks next without saving and the data is gone.Sheepshank
Solution worked for me. I checked not only for tableRef?.current?.state?.lastEditingRow but also for tableRef?.current?.state?.showAddRow as mentioned by @TomMüller . This solution passively waits for the user to click the button and then shows an alert. In my case I want to disable the button proactively since it's an OK button on a dialog box. I don't want users thinking they can save when the data is dirty.Fogdog
S
1

You can use a "useRef callback" and set a state hook, exemple :

// Create a state
const [isTableIsEditMode, setIsTableIsEditMode] = useState(false);
// Create a callback
const editRowRef = useCallback((editRow: React.ReactElement<any>) => setIsTableIsEditMode(!!editRow), []);
// Use the call back as a ref in your table for the Edit Row
// the ref is null if the table is not in edit mode
return <MaterialTable
        components={{
            ...
            EditRow: (props) => {
                return <MTableEditRow {...props} ref={editRowRef} />;
            },
        }}
        ...
    />
Sty answered 16/7, 2021 at 9:39 Comment(1)
Worked for adding a new row but for editing a row, the callback was called twice, once with an editRow and once with an undefined editRow. Consequently, it prevents editing the row. This is with "@material-table/core": "^6.1.17"Fogdog

© 2022 - 2024 — McMap. All rights reserved.