3

How to filter by date greater than current value in Material table?

This is what I managed so far, it's filtering by exact date and I need to filter all values which are >= that current value in table.

 <TableMaterial
    title=""
    columns={[  
    { title: `${t('description')}`, field: 'description' },
    {title: `${t('due_date')}`, field: 'due_date', type: 'date', align: 'center',
       filterComponent: (props) => <CustomDatePicker {...props} />}
    }]
     data={allData}
    />

And this is CustomDatePicker

const CustomDatePicker = (props) => {
  const [date, setDate] = useState(null);
  return (
    <MuiPickersUtilsProvider utils={DateFnsUtils}>
      <KeyboardDatePicker
        id="date-picker-dialog"
        format="dd/MM/yyyy"
        clearable
        value={date}
        onChange={(event) => {
          setDate(event);
          props.onFilterChanged(props.columnDef.tableData.id, event);
        }}
        KeyboardButtonProps={{
          "aria-label": "change date"
        }}
      />
    </MuiPickersUtilsProvider>
  );
};

Any help is appreciated. Thank you!

HardRock
  • 809
  • 2
  • 12
  • 37

1 Answers1

1

I managed to solve this without CustomDatePicker component, since material table has already built in date picker when field type:date is set.

So what is needed is only function and to call it in Material Table:

const handleDateFilter = (term, rowData) => {
  return new Date(term).setHours(0, 0, 0, 0) <= new Date(rowData.due_date)
    ? true
    : false;
};

<TableMaterial
  title=""
  columns={[
    { title: `${t("description")}`, field: "description" },
    {
      title: `${t("due_date")}`,
      field: "due_date",
      type: "date",
      align: "center",
      customFilterAndSearch: (term, rowData) => handleDateFilter(term, rowData),
    },
  ]}
  data={allData}
/>
Kundan
  • 1,754
  • 16
  • 37
HardRock
  • 809
  • 2
  • 12
  • 37
  • It worked! But how to select the date in YYYY-MM-DD format? – Ibad Shaikh Jul 25 '22 at 14:16
  • FYI: there's a bit more refactoring since setHours returns a number object rather than a Date object (probably just wrapping new Date().setHours() in another new Date() call), but you can remove the ?: at the end of handleDateFilter's return statement. – Artorias2718 Dec 01 '22 at 20:36