Published on

Implementing Date Range Filter with shadcn/ui Data-Table

Authors
  • Name
    Ripal & Zalak
    Twitter

Implementing a Date Range Filter with shadcn/ui Data-Table

Are you working with the shadcn/ui Data-Table and need to add a Date Range Picker to filter data? This guide will show you step-by-step how to implement a robust and user-friendly date range filter in your React application.

Overview

The shadcn/ui library provides an excellent Data-Table component for building modern React applications. However, combining it with a Date Range Picker for filtering data may seem challenging at first. This tutorial walks you through setting up a Date Range Picker and wiring it to filter your data effectively.

Prerequisites

Before proceeding, ensure you have the following installed:

  • React
  • Next.js
  • shadcn/ui
  • TanStack Table (formerly React Table) for managing the Data-Table

Step 1: Date Range Picker Component

Here is the code for your Date Range Picker component:

import { Button } from 'shadcn/ui/button'
import { Popover, PopoverTrigger, PopoverContent } from 'shadcn/ui/popover'
import { Calendar } from 'shadcn/ui/calendar'
import { CalendarIcon } from 'shadcn/ui/icons'
import { format } from 'date-fns'
import cn from 'classnames'

export function DateRangePicker({ date, setDate }) {
  return (
    <div className={cn('grid gap-2')}>
      <Popover>
        <PopoverTrigger asChild>
          <Button
            id="date"
            variant="outline"
            className={cn(
              'w-[300px] justify-start text-left font-normal',
              !date && 'text-muted-foreground'
            )}
          >
            <CalendarIcon className="mr-2 h-4 w-4" />
            {date?.from ? (
              date.to ? (
                `${format(date.from, 'LLL dd, y')} - ${format(date.to, 'LLL dd, y')}`
              ) : (
                format(date.from, 'LLL dd, y')
              )
            ) : (
              <span>Pick a date</span>
            )}
          </Button>
        </PopoverTrigger>
        <PopoverContent className="w-auto p-0" align="start">
          <Calendar
            initialFocus
            mode="range"
            defaultMonth={date?.from}
            selected={date}
            onSelect={setDate}
            numberOfMonths={2}
          />
        </PopoverContent>
      </Popover>
    </div>
  )
}

Key Features

  • Button with CalendarIcon: Displays the selected date range or a placeholder.
  • Popover: Shows the date picker on click.
  • Calendar Component: Allows selecting a date range.

Step 2: Parent Component with State Management

Create a state in your parent component to manage the selected date range and pass it to the Date Range Picker.

import { useState } from 'react'
import { DateRangePicker } from './DateRangePicker'

export default function App() {
  const [dateRange, setDateRange] = useState(null)

  return (
    <div>
      <DateRangePicker date={dateRange} setDate={setDateRange} />
    </div>
  )
}

Step 3: Filtering Data in the Data-Table

To filter the data based on the selected date range, use the following steps:

Create a Filter Callback

Define a filter function that checks if the data falls within the selected date range.

function filterByDateRange(data, dateRange) {
  if (!dateRange?.from || !dateRange?.to) return data

  return data.filter((item) => {
    const itemDate = new Date(item.date) // Adjust "date" to your data field
    return itemDate >= new Date(dateRange.from) && itemDate <= new Date(dateRange.to)
  })
}

Integrate with the Data-Table

Pass the filtered data to the Data-Table.

import { useMemo } from 'react'
import { Table } from 'shadcn/ui/table'

export default function DataTable({ data, dateRange }) {
  const filteredData = useMemo(() => filterByDateRange(data, dateRange), [data, dateRange])

  return <Table data={filteredData} columns={columns} />
}

Step 4: Adding an Apply Button

Enhance usability by adding an Apply button below the calendar.

<Button
  className="mb-4 ml-3"
  size="sm"
  onClick={() => console.log('Applied date range:', dateRange)}
>
  Apply
</Button>

FAQs

1. Why isn’t my Date Range Picker working?

Ensure that the onSelect handler in the Calendar component updates the state correctly. Also, verify that the date format matches your data.

2. How can I style the components?

Use the className prop to apply custom styles or utilities from Tailwind CSS.

3. Can I use this in Next.js?

Yes, the code works seamlessly with Next.js. Import the components and include them in your pages or components.

Conclusion

Adding a Date Range Picker to filter a shadcn/ui Data-Table enhances user experience and makes data exploration intuitive. With this guide, you can implement this feature and customize it further based on your needs.