# Booking Slot Picker
*URL: https://www.grettech.com/components/booking-slot-picker*

Pick a day, then a time. A "book a call" widget for consultants, clinics and agencies, without a third-party embed.

- Week-by-week day strip with closed days marked
- Your own availability through getSlots
- Past slots today are hidden; times shown in the visitor's time zone
- 12- or 24-hour times in any locale

## Install with the shadcn CLI
```bash
npx shadcn@latest add https://www.grettech.com/api/registry/booking-slot-picker
```
With its demo: `npx shadcn@latest add https://www.grettech.com/api/registry/booking-slot-picker-demo`

**Dependencies:** npm: clsx, tailwind-merge, lucide-react; shadcn/ui: button

## Manual installation
**Step 1: Install dependencies**
Install the packages this component uses and the shadcn/ui components it builds on. It also needs the `cn` helper in `lib/utils.ts`, which `npx shadcn@latest init` adds.

```bash
npm install clsx tailwind-merge lucide-react
npx shadcn@latest add button
```

**Step 2: Copy the source code**
Add these files to your project components directory.

File: `components/ui/booking-slot-picker.tsx`
```tsx
"use client"

import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils"
import { CalendarCheck, ChevronLeft, ChevronRight, Globe } from "lucide-react"
import * as React from "react"

export interface BookingSelection {
  /** "2026-10-14" */
  date: string
  /** "09:30", 24-hour */
  time: string
}

export interface BookingSlotPickerProps extends Omit<
  React.HTMLAttributes<HTMLDivElement>,
  "onChange"
> {
  /** First bookable day, "YYYY-MM-DD". Defaults to today (set after mount). */
  startDate?: string
  /** How many days can be booked from startDate */
  days?: number
  /** Free slots for a day ("HH:MM", 24-hour). Return [] for a closed day. */
  getSlots?: (date: string) => string[]
  value?: BookingSelection | null
  onChange?: (selection: BookingSelection | null) => void
  /** Called with the chosen slot when the confirm button is pressed */
  onConfirm?: (selection: BookingSelection) => void
  hourCycle?: 12 | 24
  locale?: string
  title?: string
  /** Hides the visitor's time zone note */
  hideTimeZone?: boolean
}

const DAY_MS = 86_400_000

/** Dates as UTC midnights, so "YYYY-MM-DD" never shifts with time zones */
const parse = (iso: string) => Date.parse(`${iso}T00:00:00Z`)
const toIso = (ms: number) => new Date(ms).toISOString().slice(0, 10)

/** Weekdays, 09:00–17:00 every 30 minutes */
export function defaultSlots(date: string) {
  const day = new Date(parse(date)).getUTCDay()
  if (day === 0 || day === 6) return []
  return Array.from({ length: 16 }, (_, i) => {
    const minutes = 9 * 60 + i * 30
    return `${String(Math.floor(minutes / 60)).padStart(2, "0")}:${String(minutes % 60).padStart(2, "0")}`
  })
}

const VISIBLE_DAYS = 7

export const BookingSlotPicker = React.forwardRef<
  HTMLDivElement,
  BookingSlotPickerProps
>(
  (
    {
      startDate,
      days = 21,
      getSlots = defaultSlots,
      value: controlledValue,
      onChange,
      onConfirm,
      hourCycle = 12,
      locale = "en-US",
      title = "Book a call",
      hideTimeZone = false,
      className,
      ...props
    },
    ref
  ) => {
    // Today is only known in the browser; reading it during render would
    // differ between server and client
    const [today, setToday] = React.useState<string | null>(null)
    const [timeZone, setTimeZone] = React.useState<string | null>(null)
    const [nowMinutes, setNowMinutes] = React.useState(0)
    React.useEffect(() => {
      const now = new Date()
      setNowMinutes(now.getHours() * 60 + now.getMinutes())
      setToday(
        `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`
      )
      setTimeZone(Intl.DateTimeFormat().resolvedOptions().timeZone)
    }, [])
    const start = startDate ?? today

    const allDays = React.useMemo(
      () =>
        start
          ? Array.from({ length: days }, (_, i) => {
              const iso = toIso(parse(start) + i * DAY_MS)
              let slots = getSlots(iso)
              // Slots earlier today have passed
              if (iso === today) {
                slots = slots.filter((t) => {
                  const [h, m] = t.split(":").map(Number)
                  return h * 60 + m > nowMinutes
                })
              }
              return { iso, slots }
            })
          : [],
      [start, days, getSlots, today, nowMinutes]
    )

    const [internalValue, setInternalValue] =
      React.useState<BookingSelection | null>(null)
    const value =
      controlledValue !== undefined ? controlledValue : internalValue
    const select = (next: BookingSelection | null) => {
      setInternalValue(next)
      onChange?.(next)
    }

    const firstOpen = allDays.find((d) => d.slots.length > 0)?.iso ?? null
    const [activeDay, setActiveDay] = React.useState<string | null>(null)
    const day = activeDay ?? value?.date ?? firstOpen
    const daySlots = allDays.find((d) => d.iso === day)?.slots ?? []

    const [page, setPage] = React.useState(0)
    const pages = Math.max(1, Math.ceil(allDays.length / VISIBLE_DAYS))
    const visible = allDays.slice(
      page * VISIBLE_DAYS,
      (page + 1) * VISIBLE_DAYS
    )

    const fmt = React.useMemo(
      () => ({
        weekday: new Intl.DateTimeFormat(locale, {
          weekday: "short",
          timeZone: "UTC",
        }),
        month: new Intl.DateTimeFormat(locale, {
          month: "long",
          year: "numeric",
          timeZone: "UTC",
        }),
        long: new Intl.DateTimeFormat(locale, {
          weekday: "long",
          day: "numeric",
          month: "long",
          timeZone: "UTC",
        }),
        time: new Intl.DateTimeFormat(locale, {
          hour: "numeric",
          minute: "2-digit",
          hourCycle: hourCycle === 12 ? "h12" : "h23",
          timeZone: "UTC",
        }),
      }),
      [locale, hourCycle]
    )
    const formatTime = (time: string) =>
      fmt.time.format(new Date(`1970-01-01T${time}:00Z`))

    return (
      <div
        ref={ref}
        className={cn(
          "w-full max-w-md rounded-2xl border bg-card p-5 text-card-foreground shadow-sm",
          className
        )}
        {...props}
      >
        <div className="flex items-center justify-between gap-3">
          <div>
            <h3 className="text-base font-semibold">{title}</h3>
            <p className="text-sm text-muted-foreground">
              {visible[0] ? fmt.month.format(parse(visible[0].iso)) : " "}
            </p>
          </div>
          <div className="flex gap-1">
            <Button
              type="button"
              variant="outline"
              size="icon"
              className="size-8"
              aria-label="Earlier days"
              disabled={page === 0}
              onClick={() => setPage((p) => p - 1)}
            >
              <ChevronLeft className="size-4" />
            </Button>
            <Button
              type="button"
              variant="outline"
              size="icon"
              className="size-8"
              aria-label="Later days"
              disabled={page >= pages - 1}
              onClick={() => setPage((p) => p + 1)}
            >
              <ChevronRight className="size-4" />
            </Button>
          </div>
        </div>

        <div
          role="group"
          aria-label="Day"
          className="mt-4 grid grid-cols-7 gap-1.5"
        >
          {visible.length === 0
            ? // Placeholder row until today is known
              Array.from({ length: VISIBLE_DAYS }, (_, i) => (
                <div key={i} className="h-16 rounded-xl bg-muted" />
              ))
            : visible.map(({ iso, slots }) => {
                const date = new Date(parse(iso))
                const active = iso === day
                const closed = slots.length === 0
                return (
                  <button
                    key={iso}
                    type="button"
                    disabled={closed}
                    aria-pressed={active}
                    aria-label={`${fmt.long.format(date)}${closed ? ", no free slots" : `, ${slots.length} free slots`}`}
                    onClick={() => setActiveDay(iso)}
                    className={cn(
                      "flex h-16 flex-col items-center justify-center gap-0.5 rounded-xl border text-sm transition-colors focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",
                      active
                        ? "border-foreground bg-foreground text-background"
                        : "hover:border-foreground/30 hover:bg-muted",
                      closed &&
                        "cursor-not-allowed border-dashed opacity-40 hover:bg-transparent"
                    )}
                  >
                    <span
                      className={cn(
                        "text-[11px] uppercase",
                        active ? "text-background/70" : "text-muted-foreground"
                      )}
                    >
                      {fmt.weekday.format(date)}
                    </span>
                    <span className="font-semibold tabular-nums">
                      {date.getUTCDate()}
                    </span>
                  </button>
                )
              })}
        </div>

        <div className="mt-5">
          <p className="text-xs font-medium text-muted-foreground">
            {day ? fmt.long.format(parse(day)) : "Pick a day"}
          </p>
          <div
            role="group"
            aria-label="Time"
            className="mt-2 grid h-44 auto-rows-min grid-cols-3 gap-1.5 overflow-y-auto pr-1 sm:grid-cols-4"
          >
            {day &&
              daySlots.map((time) => {
                const active = value?.date === day && value.time === time
                return (
                  <button
                    key={time}
                    type="button"
                    aria-pressed={active}
                    onClick={() => select(active ? null : { date: day, time })}
                    className={cn(
                      "rounded-lg border py-2 text-sm tabular-nums transition-colors focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",
                      active
                        ? "border-foreground bg-foreground text-background"
                        : "hover:border-foreground/30 hover:bg-muted"
                    )}
                  >
                    {formatTime(time)}
                  </button>
                )
              })}
          </div>
        </div>

        <div className="mt-5 flex flex-col gap-3 border-t pt-4">
          {!hideTimeZone && (
            <p className="flex items-center gap-1.5 text-xs text-muted-foreground">
              <Globe aria-hidden="true" className="size-3.5" />
              Times are in your time zone{timeZone ? ` (${timeZone})` : ""}
            </p>
          )}
          <Button
            type="button"
            disabled={!value}
            onClick={() => value && onConfirm?.(value)}
          >
            <CalendarCheck aria-hidden="true" />
            {value
              ? `Book ${formatTime(value.time)}, ${fmt.long.format(parse(value.date))}`
              : "Choose a time"}
          </Button>
        </div>
      </div>
    )
  }
)
BookingSlotPicker.displayName = "BookingSlotPicker"

```

**Step 3: Framework Adjustments (Optional)**
If you are manually copying this code into a Vite or Remix project (without using the CLI), make sure to remove the `"use client";` directive from the very top of the file.

## Props
| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| `startDate` | `string` | - | No | First bookable day, "YYYY-MM-DD". Defaults to today, worked out in the browser after load; pass it to render days on the server. |
| `days` | `number` | `21` | No | How many days can be booked from startDate. |
| `getSlots` | `(date: string) => string[]` | `defaultSlots` | No | Free slots for a day as 24-hour "HH:MM" strings. Return [] for a closed day. The default is weekdays 09:00–17:00 every 30 minutes (exported as defaultSlots). |
| `value` | `BookingSelection \| null` | - | No | Controlled selection: { date: "YYYY-MM-DD", time: "HH:MM" }. |
| `onChange` | `(selection: BookingSelection \| null) => void` | - | No | Called when a slot is picked or cleared. |
| `onConfirm` | `(selection: BookingSelection) => void` | - | No | Called when the visitor presses the book button. |
| `hourCycle` | `12 \| 24` | `12` | No | Time format. |
| `locale` | `string` | `"en-US"` | No | Locale for day and time labels. |
| `title` | `string` | `"Book a call"` | No | Heading. |
| `hideTimeZone` | `boolean` | `false` | No | Hides the time zone note. |
| `className` | `string` | - | No | Extra classes for the card. |
| `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | No | Any other attributes, passed to the card. |

## Usage
```tsx
"use client"

import { useState } from "react"
import {
  BookingSlotPicker,
  type BookingSelection,
} from "@/components/ui/booking-slot-picker"

export default function BookingSlotPickerDemo() {
  const [booked, setBooked] = useState<BookingSelection | null>(null)

  return (
    <div className="flex w-full flex-col items-center gap-3 p-4">
      <BookingSlotPicker onConfirm={setBooked} />
      <p className="h-5 text-sm text-muted-foreground" aria-live="polite">
        {booked && `Requested ${booked.date} at ${booked.time}`}
      </p>
    </div>
  )
}

```
