Reputation: 63
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!
Upvotes: 5
Views: 12841
Reputation: 71
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}
/>
Upvotes: 7