Andriy Kharchuk
Andriy Kharchuk

Reputation: 1304

Displaying Index column in mui-datatables

I have a requirement to display row index for every row in my table. I see two options:

Both options have some downsides. And I am surprised this feature doesn't come out-of-the box.

Are there some other options? I would prefer to be able to load all data into the browser, but with customRowRender I won't be able to keep original row styling...

Upvotes: 1

Views: 3660

Answers (2)

Wainaina Nik
Wainaina Nik

Reputation: 193

use customBodyRender pass rowIndex and dataIndex, then access dataIndex.rowIndex it has worked for me

        name: "id",
        label: "#",
        options: {
            filter: true,
            sort: true,
            customBodyRender: (rowIndex, dataIndex) => dataIndex.rowIndex + 1 
        }
    },

increment with 1 to start at position 1

Upvotes: 0

Andriy Kharchuk
Andriy Kharchuk

Reputation: 1304

The solution is to add an extra column to a source dataset with undefined or empty string value and then to use a custom cell body render function:

export function customRowIndexColumn() {
    return ({
        name: '#',
        options: {
            filter: false,
            customBodyRender: (value: any, meta: MUIDataTableMeta) => {
                return (
                    meta.rowIndex + 1
                );
            }
        }
    })
}
....

    const columns: MUIDataTableColumnDef[] = [
        customRowIndexColumn(),
        {
            name: 'Plane ID',
            options: {
                filter: false
            }
        },
        {
            name: 'Name',
            options: {
                filter: false
            }
        },
...

Upvotes: 2

Related Questions