[SOLVED] date range with ShadCN

The way i work it is...

// columns.jsx

{
    id: "created_at",
    accessorKey: "created_at",
    header: ({ column }) => {
      return (
        <Button
          variant="ghost"
          onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}>
          Fecha
          <ArrowUpDown className="ml-2 h-4 w-4" />
        </Button>
      )
    },
    cell: ({ row }) => {
      const date = new Date(row.getValue("created_at"))
      const formated = format(date, "EEE, dd 'de' MMMM yyyy", { locale: es })

      return <div>{formated}</div>
    },
    filterFn: "dateRange" as FilterFnOption<Transactions>, // here you have to put the tag (my case,'dateRange') you put on your function
  }




// data-table.jsx

// Outside from the component DataTable
const dateRangeFilter: FilterFn<Transactions> = ( // 'Transactions' is my type of rows i'm working with, you can use ANY
  row,
  columnId,
  filterValue = { from: new Date(0), to: new Date() }
) => {
  const rowValue = new Date(row.getValue(columnId))
  const { from, to } = filterValue
  return rowValue >= from && rowValue <= to
}



const table = useReactTable({
    data,
    columns,
    getCoreRowModel: getCoreRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    onSortingChange: setSorting,
    getSortedRowModel: getSortedRowModel(),
    onColumnFiltersChange: setColumnFilters,
    getFilteredRowModel: getFilteredRowModel(),
    onColumnVisibilityChange: setColumnVisibility,
    state: {
      sorting,
      columnFilters,
      columnVisibility,
    },
    filterFns: {
      dateRange: dateRangeFilter, // dateRange is the tag i was talking about above. `dateRangeFilter` the name of above function
    },
  })



then you have to call the column where the datees are and set the filter value with the range you want
    table.getColumn("created_at")?.setFilterValue(newDateRange)
Was this page helpful?