Search code examples
javascriptreactjsmaterial-uimaterial-table

How to make just 1 row editable in material-table?


Currently I have a table of my employees using material-table. There are some employees with certain flags which make the background row red. This is what it looks like:

enter image description here

What I want to do is to be able to edit the rows with the red backgrounds and only these rows. I don't want to put the editable prop on the entire table because that would take up space with icons for every single row, but I only want to be able to edit the rows with these special flags.

Here is my React code. Note that forgotClockOut is the special flag that I have.

<MaterialTable
    icons={icons}
    title="Daily Report"
    columns={[
        { title: 'Name', field: 'name' },
        {
            title: 'Time In',
            field: 'started',
            render: ({ started }) =>
                started
                    ? moment(started).format('h:mm A')
                    : 'Not yet',
            cellStyle: (value, { started, clockedOut }) => {
                if (!started) {
                    return null;
                }

                if (clockedOut) {
                    return { color: 'red' };
                }

                return { color: '#06c92d' };
            },
        },
        { title: 'Time Out', field: 'clockedOut', render: ({clockedOut}) => clockedOut ? moment(clockedOut).format('h:mm A') : 'Not yet'},
        { title: 'Time Worked', field: 'minutesWorked', render: ({minutesWorked}) => `${Math.floor(minutesWorked / 60)}h ${minutesWorked % 60}m`},
    ]}
    options={{
        rowStyle: ({forgotClockOut}) => {
            if(forgotClockOut) {
                return { backgroundColor: '#ffaaaa' };
            }
        }
    }}
    onRowClick={(event, rowData) => {
        const {forgotClockOut} = rowData;
        // ?? What to do here ??
    }}
    data={employees}
/>

Is there any way to only edit certain rows in a table made using material-table?


Solution

  • You can use the edit prop to define that:

    <MaterialTable
        editable={{
            isEditable: rowData => rowData.name === 'a', // only name(a) rows would be editable
    }}/>
    

    You can see that in docs: https://material-table.com/#/docs/features/editable