Display rows with current date as top result using react-table

Viewed 448

I'm trying to create a table using react-table that would display data that matches today's date as the top result. For instance, today is 18 August 2021, so I would like any data entry that matches 08/18/2021 (mm/dd/yyyy format) to be displayed as the topmost entry in my table.

My current table looks like this

To give an example, I have already sorted my table in chronological order (from earliest to latest in mm/dd/yyyy format). However, I want any entry/entries in the table above with today's date (eg. Date of Operation: 08/18/2021) to be displayed at the top of the table. Thereafter, entries that do not match today's date will continue to be sorted in chronological order.

Can someone please let me know how this can be done? Thank you.

2 Answers

Without getting into the code details, you should be able to do this by supplying a custom sort function in the column definition API docs. We don't do this specific sort but we do have multiple custom sort functions, and I got the most help in writing them by reading the sortTypes.js file from the library source.

Here's a simple date sort function. You basically get two rows and a columnId and return -1, 0, or 1.

    const prevDate = new Date(prev.original[columnId])
    const prevIsDate = ...
    const currDate = new Date(curr.original[columnId])
    const currIsDate = ...
    if (prevIsDate && currIsDate) {
      return prevDate > currDate ? 1 : -1
    } else {
      if (!prevIsDate) {
        return !currIsDate ? 0 : 1
      } else {
        return 1
      }
    }
  }
Related