Getting started
Examples
- Examples
- Booking calendar
- Team calendar
- Room booking
- Shift scheduler
- Conference agenda
- Calendar in an app layout
- Optimistic server sync
- Lazy-load by date range
- View and date in the URL
- Custom persistence adapter
- ICS import and export
- Custom event rendering
- Multiple time zones
- Linked month and day views
- Recurring events (RRULE)
- Custom ⌘K commands
- Natural-language event entry
Registry
Core concepts
Customization
View and date in the URL
Controlled view and date mirrored into the query string, so a link opens the same week and the browser's back button steps the calendar.
Step forward and look at the address bar: ?view=…&date=… follows. Switch
to month view; it follows again. Press the browser's back button and the
calendar steps back to the date you came from. Copy the link, open it in
another tab, and it lands on the same view of the same date — a calendar you
can share. The link always names the view on screen: in a box too narrow for
a week it reads view=day, because a day is what is drawn.
live·View and date in the URL
loading
"use client";
import {
buildSeedEvents,
Kloq,
type KloqView,
MAX_N_DAY_VIEW,
MIN_N_DAY_VIEW,
parseInstant,
toDateOnlyString,
} from "kloq";
import { usePathname } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import { CopyButton } from "@/components/calendar/site/copy-button";
import { Bar } from "../parts";
const NAMED: KloqView[] = ["day", "week", "month", "agenda", "year"];
function parseView(s: string | null): KloqView | null {
if (NAMED.includes(s as KloqView)) return s as KloqView;
const n = Number(s);
return Number.isInteger(n) && n >= MIN_N_DAY_VIEW && n <= MAX_N_DAY_VIEW ? n : null;
}
/** `YYYY-MM-DD` at local midnight; anything else — including a rolled-over 2026-02-31 — is rejected. */
function parseDate(s: string | null): Date | null {
if (!s) return null;
const d = new Date(parseInstant(s));
return Number.isNaN(d.getTime()) || toDateOnlyString(d) !== s ? null : d;
}
function fromQuery(search: string) {
const params = new URLSearchParams(search);
return {
view: parseView(params.get("view")) ?? "week",
date: parseDate(params.get("date")) ?? new Date(),
};
}
const toQuery = (view: KloqView, date: Date) => `?view=${view}&date=${toDateOnlyString(date)}`;
export default function UrlStateExample() {
const pathname = usePathname();
// the query string is the state; null until the location has been read
const [search, setSearch] = useState<string | null>(null);
const { view, date } = useMemo(() => fromQuery(search ?? ""), [search]);
const [seeds] = useState(() => buildSeedEvents());
useEffect(() => {
const read = () => setSearch(window.location.search);
// normalise the incoming link: missing or invalid params become today's week
const initial = fromQuery(window.location.search);
window.history.replaceState(null, "", toQuery(initial.view, initial.date));
read();
window.addEventListener("popstate", read);
return () => window.removeEventListener("popstate", read);
}, []);
// a date is somewhere you went, so it gets a history entry; a view is how you are looking at it —
// and a narrow box reports the view it collapsed to — so it rewrites the entry it is on
const navigate = (next: { view?: KloqView; date?: Date }) => {
const query = toQuery(next.view ?? view, next.date ?? date);
if (query === search) return;
if (next.date) window.history.pushState(null, "", query);
else window.history.replaceState(null, "", query);
setSearch(query);
};
return (
<div className="@container flex flex-col">
<div className="h-104">
<Kloq
view={view}
onViewChange={(v) => navigate({ view: v })}
date={date}
onDateChange={(d) => navigate({ date: d })}
defaultEvents={seeds}
persistence={false}
storage={false}
designMode={false}
>
<Kloq.Toolbar />
</Kloq>
</div>
<Bar edge="top">
<span className="min-w-0 flex-1 wrap-anywhere">
{pathname}
<span className="text-foreground">{search ?? ""}</span>
</span>
<CopyButton
size="xs"
variant="outline"
showLabel
label="Copy link"
text={() => window.location.href}
/>
</Bar>
</div>
);
}
"use client";
import { Button } from "@coss/ui/components/button";
import { cn } from "@coss/ui/lib/utils";
import { formatViewTitle, useIsClient, useKloq } from "kloq";
import { ChevronLeft, ChevronRight } from "lucide-react";
import type { ComponentProps } from "react";
/** The strip an example hangs its controls and readouts on; same box as `Kloq.Toolbar`. */
export function Bar({
edge = "bottom",
className,
...props
}: ComponentProps<"div"> & { edge?: "top" | "bottom" }) {
return (
<div
{...props}
className={cn(
"flex min-h-11 shrink-0 flex-wrap items-center gap-x-4 gap-y-2 px-4 py-2.5 font-mono text-xs text-muted-foreground",
edge === "bottom" ? "border-b" : "border-t",
className,
)}
/>
);
}
export function Dot({ live, className, ...props }: ComponentProps<"span"> & { live?: boolean }) {
return (
<span
aria-hidden
{...props}
className={cn(
"size-1.5 shrink-0 rounded-full",
live ? "bg-brand motion-safe:animate-pulse" : "bg-border",
className,
)}
/>
);
}
/** Previous / next / today for a calendar whose view is fixed. Must render inside `<Kloq>`. */
export function Nav({ locale }: { locale?: string }) {
const k = useKloq();
const isClient = useIsClient();
return (
<div className="flex min-w-0 items-center gap-1">
<Button variant="ghost" size="icon-xs" aria-label="Previous" onClick={() => k.step(-1)}>
<ChevronLeft />
</Button>
<Button variant="ghost" size="icon-xs" aria-label="Next" onClick={() => k.step(1)}>
<ChevronRight />
</Button>
<Button
variant="ghost"
size="xs"
className={cn(k.atToday && "text-muted-foreground")}
onClick={k.goToday}
>
Today
</Button>
<span className="ms-1 truncate text-sm font-medium text-foreground tabular-nums sm:text-xs">
{isClient ? formatViewTitle(k.view, locale, { short: k.narrow }) : null}
</span>
</div>
);
}
usesviewdateonViewChangeonDateChange
How it works
viewanddateare controlled. With both props set, ‹ ›, Today, the view switcher, the month picker and the arrow keys all ask throughonViewChange/onDateChange, and nothing moves until the props change. That is what makes the URL authoritative: the calendar cannot drift from it. See Controlled state.- The query string is the state.
searchholds it verbatim;viewanddateare derived from it withuseMemo.navigatebuilds the next string, writes it withwindow.history, and stores it — no router navigation, no server round-trip. A new date ispushState, so back and forward walk the dates you visited; a new view isreplaceState, so it rewrites the entry it is on. Next.js patches both, souseSearchParamselsewhere on the page stays in sync for free. - Back and forward are a
popstatelistener that readslocation.searchback into state. The initial read runs in an effect, never during render, so the server-rendered markup and the first client paint agree; it alsoreplaceStates a normalised query, so a bare or broken link becomes?view=week&date=<today>without adding a history entry. - Parsing is strict.
parseViewaccepts the five named views and an n-day integer insideMIN_N_DAY_VIEW … MAX_N_DAY_VIEW;parseDateacceptsYYYY-MM-DDonly, and rejects a date that would roll over by checking that the parsedDateformats back — throughtoDateOnlyString— to the same string. Anything else falls back to today's week. See Views & navigation. - The chrome is the stock
<Kloq.Toolbar />. Its parts read the same controlled state throughuseKloq(), which is why they need no wiring. See Toolbar & chrome. - The responsive collapse stays on, and the URL follows it. A box under 900px
squeezes a week to three days, one under 640px to a single day, and kloq
reports that effective view through
onViewChange; widen the box and it asks for the week back the same way. Because a view change replaces the history entry, the width can rewrite the link as often as it likes without piling up entries or trapping the back button. See Views & navigation.
Take it further
- Prefer one history entry per visit? Use
replaceStatefor dates too — the link still shares, the back button leaves the page. - Put it in the path instead:
/kloq/week/2026-08-31. The parsing does not change; readusePathname()instead oflocation.search. - Keep the intent in the URL instead of the view on screen: a child of
<Kloq>can readuseKloq().collapsed, and a view change reported while it is true is the width talking, not the user — ignore it and the link saysweekon every device.
Last updated
On This Page