How to add a serial number to every row in MUI DataGrid?

Viewed 1263

First, some data is requested from the server.And then I want to add some data.There is no ID in the data value, but the form needs to display the serial number.

 const columns: GridColDef[] = [
        { 
            field: 'id' , 
            headerName: 'number', 
            filterable: false,
            renderCell:(index:any) => `${index + 1}`
        },
        { field: 'code' , headerName: ' code' },
        { field: 'type' , headerName: ' type' },
  ]
<DataGrid rows={row} columns={columns} />

But index is Nan.How do I generate a serial number in each line in a table when I add a new data?

3 Answers

We can achieve this by using getRowIndex method. getRowIndex method takes the filed name as a parameter and returns the index of the row to which this filed belongs. so the trick is to pass a unique field to this method.

The solution to your problem would look something like this:

Column field :

   {
        field: 'id' , 
        headerName: 'number', 
        filterable: false,
        renderCell:(index) => index.api.getRowIndex(index.row.code)
    }

Data Grid :

<DataGrid rows={row} columns={columns} getRowId= {(row) => row.code}/>

In the above example I am asuming that code is a unique field. If its hard to have a unique field, you can generate one field with combinations of code, type and so on.

In this case your solution would look something like this:

Column field :

   {
        field: 'id' , 
        headerName: 'number', 
        filterable: false,
        renderCell:(index) => index.api.getRowIndex(index.row.code + '_' + index.row.type)
    }

Data Grid :

<DataGrid rows={row} columns={columns} getRowId= {(row) => row.code + '_' + row.type}/>

I was able to get the row index by calling the getRowIndex from the api:

renderCell: (index) => index.api.getRowIndex(index.row.id) + 1,

So using your example:

 const columns: GridColDef[] = [
        { 
            field: 'id' , 
            headerName: 'number', 
            filterable: false,
            renderCell: (index) => index.api.getRowIndex(index.row.id) + 1,
        },
        { field: 'code' , headerName: ' code' },
        { field: 'type' , headerName: ' type' },
  ]

If a column has sortable: true, this index number won't change regardless of how the column is sorted - it will always be 1 for the first line item, 2 for the second, etc.

Likewise, for grids with pagination enabled, the index will match based on the page (ie: if there are 5 line items per page, regardless of sorting, the first line item will always be 1 on page 1, 6 on page 2, etc).

You can use renderCell method, and its prop has a key of id which is unique for every row. It would look something like this.

renderCell: (params) => {
   return (<h1>
            {'serial Number:', params.id}
           </h1>);
        }

You can also use the npm package nanoid to generate a unique id for every row.

Related