reactjsreact-data-table-component

Adding serial number column in the table


I am using a library named react-data-table-component for table in my application. Everything is going pretty smooth however I need to add a column which will show serial number in my table. The serial number will always start from 1 to total number of objects in photos array.

const columns = [
    {
      name: '#',
      selector: 'id',
      cell: (row) => <span>{I need to show serial number here}</span>
    },
    {
      name: 'Name',
      selector: 'photo_link',
      sortable: true,
    }
    ... // Other fields
]

<DataTable
        columns={columns}
        data={photos}
        paginationTotalRows={total_photos}

Cell key inside column array just takes row as argument and it has current object but I can't get the index of object.

I have the id field in every object of the array but that is not in sequence which I need. How do I solve this problem?


Solution

  • I think the easiest way is to add the serial number to your array items upfront.

    photos.forEach((photo, index) => { photo.serial = index + 1; });
    

    Then, simply use this serial field in your columns definition:

    {
      name: '#',
      selector: 'serial'
    }