5

I am using 'react-data-table-component' in React JS.

Following is my sample structure:

import DataTable from "react-data-table-component";

const data = myData;
const columns = [
   {
      name: 'Date',
      selector: 'dateOfAction',
      cell: row => <div>{moment(row.dateOfAction).format("MM-DD-YYYY A")}</div>,
      sortable: true,
   },
   {
      name: 'History Date',
      selector: 'dateOfAction',   
      cell: row => <div>{moment(row.dateOfAction).format("YYYY-MM-DD HH:mm:ss")}</div>,
      sortable: true,
   } 
];

<DataTable
   columns={columns}
   data={data}
   defaultSortField="dateOfAction"
   pagination
   striped
   defaultSortAsc={false}
 />

Here, Both columns have same selector.

And, I am able to sort data by first column i.e 'Date' but I want to sort table data by last column i.e 'History Date'.

How should I sort data by last column?

Thanks!

1 Answer 1

7

You can pass the defaultSortFieldId prop in the DataTable component. According to the documentation:

The defaultSortFieldId sets the a column to be pre sorted and corresponds to the a column definition id

This means that you will need to provide an unique id for each column and then pass the id you want to use to the defaultSortFieldId:

const columns = [
       {
          id: 'date',
          name: 'Date',
          selector: 'dateOfAction',
          cell: row => <div>{moment(row.dateOfAction).format("MM-DD-YYYY A")}</div>,
          sortable: true,
       },
       {
          id: 'historyDate',
          name: 'History Date',
          selector: 'dateOfAction',   
          cell: row => <div>{moment(row.dateOfAction).format("YYYY-MM-DD HH:mm:ss")}</div>,
          sortable: true,
       } 
    ];

<DataTable
   columns={columns}
   data={data}
   defaultSortFieldId="historyDate"
   pagination
   striped
   defaultSortAsc={false}
 />
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.