0

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?

wazz
  • 92
  • 1
  • 4
  • 11

5 Answers5

3

I know it's late, but posting as it would help others!

You can have a serial number with the help of index in your column definition, for example

const columns = [
  {
    name: '#',
    cell: (row, index) => index + 1  //RDT provides index by default
  },
   ... // Other fields
]

And indexes start with 0 always, so we are using + 1, Now it will start with 1.

Arvindh
  • 600
  • 1
  • 10
  • 25
2

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'
}
zord
  • 4,538
  • 2
  • 25
  • 30
  • I have 100s of photos coming in the api response. Before I render I have to do this? Is there no other way which is built in library already? – wazz May 07 '20 at 12:27
  • I haven't found a built-in way to do it in the docs. Doing this for 100s of items (once, after you fetched the data) is no big deal. I'd say it's even better that doing it all the time dynamically. Also, if you sort the array later, the pre-generated serials will be preserved, which is another advantage. – zord May 07 '20 at 16:30
0

Try this in columns

render:(text,record,index)=>`${index+1}`,
0

You were almost there.

I used below code to get the desired outcome, We can avoid adding new field ('serial' as suggested by Zord) to objects in the array.

Cell: (props) => (<span>{props.index + 1}</span>)
SRavi
  • 1
0

const columns = [ { name: '#', selector: 'id', cell: (row,index) => index+1 },

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – alea Jun 01 '23 at 12:55