Examples & playground
Every example on this page runs live, and the code under it is the exact file that runs.
Copy it into your app as it is. The examples share data.ts, a busy week of sample
events around today; it is in the second tab of each example.
The calendar fills its parent element. Give the parent a height, as every example does, and the hour views scroll inside it.
Playground
Change the options and copy the component they add up to. Options left at their defaults add nothing to the code.
import { useState } from 'react';
import Calendar, {
type CalendarView,
type CalendarItem,
} from 'react-lightweight-calendar';
export default function MyCalendar({ events }: { events: CalendarItem[] }) {
const [view, setView] = useState<CalendarView>('WEEK_TIME');
const [date, setDate] = useState<string | Date>(new Date());
return (
// The calendar fills its parent, so give the parent a height.
<div style={{ height: 640 }}>
<Calendar
data={events}
activeTimeDateField="start-end"
currentView={view}
onViewChange={setView}
currentDate={date}
setCurrentDate={setDate}
/>
</div>
);
}
Basics
Calendar with navigation
setCurrentDate shows the navigation, onViewChange the view switcher, and views
picks the views it offers.
import { useState } from 'react';
import Calendar, { type CalendarView } from 'react-lightweight-calendar';
import { createEvents } from './data';
export default function BasicCalendar() {
const [events] = useState(createEvents);
const [view, setView] = useState<CalendarView>('WEEK_TIME');
const [date, setDate] = useState<string | Date>(new Date());
return (
// The calendar fills its parent. Give the parent a height, and the
// hour views scroll inside it.
<div style={{ height: 600 }}>
<Calendar
data={events}
activeTimeDateField="start-end"
currentView={view}
onViewChange={setView}
views={['MONTH', 'WEEK_TIME', 'DAY']}
currentDate={date}
setCurrentDate={setDate}
/>
</div>
);
}
All seven views
Month, week, a week schedule, a day, a horizontal day timeline, and the week and day grouped by hour. Overlapping items share the width like in Google Calendar, multi-day items sit in their own lanes, and items crossing midnight are split across their days.
import { useState } from 'react';
import Calendar, { type CalendarView } from 'react-lightweight-calendar';
import { createEvents } from './data';
export default function AllViews() {
const [events] = useState(createEvents);
const [view, setView] = useState<CalendarView>('MONTH');
const [date, setDate] = useState<string | Date>(new Date());
return (
<div style={{ height: 620 }}>
{/* Without `views`, the switcher offers all seven views. */}
<Calendar
data={events}
activeTimeDateField="start-end"
currentView={view}
onViewChange={setView}
currentDate={date}
setCurrentDate={setDate}
/>
</div>
);
}
Working hours and a 24-hour clock
startHour and endHour limit the hours, weekStartsOn picks the first day of the
week, and timeDateFormat sets any date-fns format .
import { useState } from 'react';
import Calendar, { type CalendarView } from 'react-lightweight-calendar';
import { createEvents } from './data';
export default function WorkingHours() {
const [events] = useState(createEvents);
const [view, setView] = useState<CalendarView>('WEEK_TIME');
const [date, setDate] = useState<string | Date>(new Date());
return (
<div style={{ height: 560 }}>
<Calendar
data={events}
activeTimeDateField="start-end"
currentView={view}
onViewChange={setView}
views={['WEEK_TIME', 'DAY', 'DAY_REVERSE']}
currentDate={date}
setCurrentDate={setDate}
// Show 7:00 to 20:00 only; items outside are cut at the edges.
startHour={7}
endHour={20}
// Sunday first, and a 24-hour clock.
weekStartsOn={0}
timeDateFormat={{ hour: 'HH:mm', time: 'HH:mm' }}
/>
</div>
);
}
A busy month
Days with more items than dayMaxItems end with “+N more”, which opens the list of
the day. 'auto' fits as many items as the cell height allows.
import { useState } from 'react';
import Calendar from 'react-lightweight-calendar';
import { createEvents } from './data';
const LIMITS = [2, 3, 'auto'] as const;
export default function BusyMonth() {
const [events] = useState(createEvents);
const [date, setDate] = useState<string | Date>(new Date());
const [dayMaxItems, setDayMaxItems] = useState<number | 'auto'>('auto');
return (
<>
<label style={{ display: 'inline-flex', gap: 8, marginBottom: 12 }}>
dayMaxItems
<select
value={dayMaxItems}
onChange={(event) => {
const value = event.target.value;
setDayMaxItems(value === 'auto' ? 'auto' : Number(value));
}}
>
{LIMITS.map((limit) => (
<option key={limit}>{limit}</option>
))}
</select>
</label>
<div style={{ height: 600 }}>
{/* Busy days end with "+N more", which opens the list of the day.
'auto' fits as many items as the cell height allows. */}
<Calendar
data={events}
activeTimeDateField="start-end"
currentView="MONTH"
currentDate={date}
setCurrentDate={setDate}
dayMaxItems={dayMaxItems}
/>
</div>
</>
);
}
Interaction
Create and edit events
Click an empty slot to add an event and an event to edit it. onCellClick receives a
DateInfo with the start of the clicked cell, and Calendar<Event>
types the items in every callback.
import { addHours, setHours } from 'date-fns';
import { useState } from 'react';
import Calendar, {
type CalendarView,
type DateInfo,
} from 'react-lightweight-calendar';
import { COLORS, createEvents, type Event } from './data';
export default function CreateAndEdit() {
const [events, setEvents] = useState(createEvents);
const [selectedId, setSelectedId] = useState<string | null>(null);
const [view, setView] = useState<CalendarView>('WEEK_TIME');
const [date, setDate] = useState<string | Date>(new Date());
const selected = events.find((event) => event.id === selectedId);
// A click on an empty slot creates a one-hour event there. Day cells of the
// month have no hour, so those events start at 9:00.
const create = ({ timeDateUTC, hour }: DateInfo) => {
const cellStart = new Date(timeDateUTC);
const start = hour === undefined ? setHours(cellStart, 9) : cellStart;
const event: Event = {
id: crypto.randomUUID(),
title: 'New event',
start: start.toISOString(),
end: addHours(start, 1).toISOString(),
bgColor: COLORS.blue,
};
setEvents((list) => [...list, event]);
setSelectedId(event.id);
};
const update = (changes: Partial<Event>) =>
setEvents((list) =>
list.map((event) =>
event.id === selectedId ? { ...event, ...changes } : event,
),
);
const remove = () => {
setEvents((list) => list.filter((event) => event.id !== selectedId));
setSelectedId(null);
};
return (
<>
<div
style={{
display: 'flex',
flexWrap: 'wrap',
gap: 8,
minHeight: 36,
marginBottom: 12,
}}
>
{selected ? (
<>
<input
aria-label="Title"
value={selected.title}
onChange={(e) => update({ title: e.target.value })}
/>
<select
aria-label="Color"
value={selected.bgColor}
onChange={(e) => update({ bgColor: e.target.value })}
>
{Object.entries(COLORS).map(([name, color]) => (
<option key={name} value={color}>
{name}
</option>
))}
</select>
<button onClick={remove}>Delete</button>
<button onClick={() => setSelectedId(null)}>Done</button>
</>
) : (
<span>
Click an empty slot to add an event, or an event to edit it.
</span>
)}
</div>
<div style={{ height: 560 }}>
{/* Calendar<Event> types the items in every callback. */}
<Calendar<Event>
data={events}
activeTimeDateField="start-end"
currentView={view}
onViewChange={setView}
views={['MONTH', 'WEEK_TIME', 'DAY']}
currentDate={date}
setCurrentDate={setDate}
onCellClick={create}
onItemClick={(event) => setSelectedId(event.id)}
/>
</div>
</>
);
}
Open a day from the month
Day numbers and weekday names report their day; switch the view to show it.
import { useState } from 'react';
import Calendar, { type CalendarView } from 'react-lightweight-calendar';
import { createEvents } from './data';
export default function DrillDown() {
const [events] = useState(createEvents);
const [view, setView] = useState<CalendarView>('MONTH');
const [date, setDate] = useState<string | Date>(new Date());
// Day numbers and weekday names report their day as `yyyy-MM-dd`.
const openDay = (day: string | Date) => {
setDate(day);
setView('DAY');
};
return (
<div style={{ height: 600 }}>
<Calendar
data={events}
activeTimeDateField="start-end"
currentView={view}
onViewChange={setView}
views={['MONTH', 'WEEK_TIME', 'DAY']}
currentDate={date}
setCurrentDate={setDate}
onDayNumberClick={openDay}
onDayStringClick={openDay}
/>
</div>
);
}
Every callback
Each callback prints what it receives. Click items, empty slots, day names, day numbers, hour labels, “+N more” and the red dot.
import { useState } from 'react';
import Calendar, {
toDateKey,
type CalendarView,
} from 'react-lightweight-calendar';
import { COLORS, createEvents } from './data';
export default function Callbacks() {
const [events] = useState(createEvents);
const [view, setView] = useState<CalendarView>('WEEK_TIME');
const [date, setDate] = useState<string | Date>(new Date());
const [log, setLog] = useState<string[]>([]);
const print = (entry: string) =>
setLog((list) => [entry, ...list].slice(0, 6));
return (
<>
<div style={{ height: 520 }}>
<Calendar
data={events}
activeTimeDateField="start-end"
currentView={view}
onViewChange={(next) => {
print(`onViewChange("${next}")`);
setView(next);
}}
views={['MONTH', 'WEEK_TIME', 'DAY', 'WEEK_IN_PLACE']}
currentDate={date}
setCurrentDate={(next) => {
print(`setCurrentDate("${next}")`);
setDate(next);
}}
dayMaxItems={2}
colorDots={[
{
color: COLORS.red,
text: 'Deadline',
date: toDateKey(new Date()),
},
]}
onItemClick={(item) =>
print(`onItemClick({ title: "${item.title}" })`)
}
onCellClick={(info) =>
print(`onCellClick({ timeDate: "${info.timeDate}" })`)
}
onCellHeaderClick={(info) =>
print(`onCellHeaderClick({ date: "${info.date}" })`)
}
onDayNumberClick={(day) => print(`onDayNumberClick("${day}")`)}
onDayStringClick={(day) => print(`onDayStringClick("${day}")`)}
onHourClick={(value) =>
print(
`onHourClick(${typeof value === 'number' ? value : `"${value.timeDate}"`})`,
)
}
onColorDotClick={(dot) =>
print(`onColorDotClick({ text: "${dot.text}" })`)
}
onMoreClick={(day, items) =>
print(`onMoreClick("${toDateKey(day)}", ${items.length} items)`)
}
/>
</div>
<ol
style={{
minHeight: 140,
margin: '12px 0 0',
fontFamily: 'monospace',
fontSize: 13,
}}
>
{log.length ? (
log.map((entry, i) => <li key={`${i}-${entry}`}>{entry}</li>)
) : (
<li>
Click items, slots, day names, day numbers, hours or the red dot.
</li>
)}
</ol>
</>
);
}
Load events for the visible range
getViewRange returns the days the calendar shows, so you fetch only those, again
whenever the view or the date changes.
import { useEffect, useState } from 'react';
import Calendar, {
getViewRange,
toDate,
toDateKey,
type CalendarView,
} from 'react-lightweight-calendar';
import { createEvents, type Event } from './data';
/** Stands in for your API: answers after 600 ms with the events in a range. */
async function fetchEvents(
from: string,
to: string,
signal: AbortSignal,
): Promise<Event[]> {
await new Promise((resolve) => setTimeout(resolve, 600));
signal.throwIfAborted();
const day = (value: string) => toDateKey(toDate(value)!);
return createEvents().filter(
(event) => day(event.start) <= to && day(event.end) >= from,
);
}
export default function LoadVisibleRange() {
const [view, setView] = useState<CalendarView>('WEEK_TIME');
const [date, setDate] = useState<string | Date>(new Date());
const [events, setEvents] = useState<Event[]>([]);
const [loading, setLoading] = useState(false);
// The days on screen, from the same helper the calendar uses.
const range = getViewRange(view, toDate(date) ?? new Date(), 1);
const from = toDateKey(range.start);
const to = toDateKey(range.end);
useEffect(() => {
const controller = new AbortController();
setLoading(true);
fetchEvents(from, to, controller.signal)
.then((loaded) => {
setEvents(loaded);
setLoading(false);
})
.catch(() => {}); // Aborted: a newer range is already loading.
return () => controller.abort();
}, [from, to]);
return (
<>
<p style={{ margin: '0 0 12px' }}>
{loading ? 'Loading' : 'Loaded'} {from} to {to}
{loading ? '…' : `: ${events.length} events`}
</p>
<div
style={{
height: 560,
opacity: loading ? 0.6 : 1,
transition: 'opacity 0.2s',
}}
>
<Calendar
data={events}
activeTimeDateField="start-end"
currentView={view}
onViewChange={setView}
views={['MONTH', 'WEEK_TIME', 'DAY']}
currentDate={date}
setCurrentDate={setDate}
weekStartsOn={1}
/>
</div>
</>
);
}
Customization
Your own toolbar
renderNavigation replaces the toolbar. It gets the title and the actions, so the
calendar keeps doing the date math.
import { useState } from 'react';
import Calendar, { type CalendarView } from 'react-lightweight-calendar';
import { createEvents } from './data';
const VIEW_NAMES: Partial<Record<CalendarView, string>> = {
MONTH: 'Month',
WEEK_TIME: 'Week',
DAY: 'Day',
};
export default function CustomToolbar() {
const [events] = useState(createEvents);
const [view, setView] = useState<CalendarView>('WEEK_TIME');
const [date, setDate] = useState<string | Date>(new Date());
return (
<div style={{ height: 600 }}>
<Calendar
data={events}
activeTimeDateField="start-end"
currentView={view}
onViewChange={setView}
views={['MONTH', 'WEEK_TIME', 'DAY']}
currentDate={date}
setCurrentDate={setDate}
// Your own toolbar; the calendar hands over the title and the actions.
renderNavigation={({
title,
goToToday,
goToPrevious,
goToNext,
views,
onViewChange,
}) => (
<div
style={{
display: 'flex',
flexWrap: 'wrap',
alignItems: 'center',
gap: 8,
}}
>
<button onClick={goToPrevious} aria-label="Previous">
‹
</button>
<button onClick={goToToday}>Today</button>
<button onClick={goToNext} aria-label="Next">
›
</button>
<strong style={{ flex: 1, fontSize: 18 }}>{title}</strong>
<select
aria-label="View"
value={view}
onChange={(e) => onViewChange?.(e.target.value as CalendarView)}
>
{views.map((v) => (
<option key={v} value={v}>
{VIEW_NAMES[v]}
</option>
))}
</select>
</div>
)}
/>
</div>
);
}
Custom items and headers
Render props replace any part: here the items, the all-day bars, the column headers and the hour labels. The calendar still lays everything out. See Custom rendering for all of them.
import { useState } from 'react';
import Calendar, { type CalendarView } from 'react-lightweight-calendar';
import { COLORS, createEvents, type Event } from './data';
export default function CustomRendering() {
const [events] = useState(createEvents);
const [view, setView] = useState<CalendarView>('WEEK_TIME');
const [date, setDate] = useState<string | Date>(new Date());
return (
<div style={{ height: 620 }}>
<Calendar<Event>
data={events}
activeTimeDateField="start-end"
currentView={view}
onViewChange={setView}
views={['MONTH', 'WEEK_TIME', 'DAY']}
currentDate={date}
setCurrentDate={setDate}
// Every item outside the all-day row. The calendar positions and sizes
// it, and what you return fills it; `info` says where it is drawn and
// how much room it has.
renderItem={(event, isHovered, info) => {
const roomy = info.view !== 'MONTH' && !info.isCompact;
return (
<div
style={{
padding: '2px 6px',
overflow: 'hidden',
borderLeft: `4px solid ${event.bgColor ?? COLORS.blue}`,
borderRadius: 6,
// The item color mixed into the calendar background, so it
// works in light and dark themes. Overlapping items stay opaque.
background: `color-mix(in srgb, ${event.bgColor ?? COLORS.blue} 22%, var(--rlc-bg, Canvas))`,
fontSize: 12,
lineHeight: 1.3,
boxShadow: isHovered
? '0 4px 12px rgb(0 0 0 / 0.2)'
: undefined,
}}
>
<strong>{event.title}</strong>
{roomy && <div>{info.timeLabel}</div>}
{roomy && event.location && <div>📍 {event.location}</div>}
</div>
);
}}
// All-day and multi-day bars.
renderHeaderItem={(event, { continuesBefore, continuesAfter }) => (
<div
style={{
display: 'flex',
alignItems: 'center',
padding: '0 8px',
borderRadius: 999,
background: event.bgColor ?? COLORS.blue,
color: '#fff',
fontSize: 12,
fontWeight: 600,
whiteSpace: 'nowrap',
overflow: 'hidden',
}}
>
{continuesBefore && '← '}
{event.title}
{continuesAfter && ' →'}
</div>
)}
// Column headers of the hour views.
renderDayHeader={({
weekdayLabel,
dayNumber,
isToday,
onDayNumberClick,
}) => (
<button
onClick={onDayNumberClick}
style={{
display: 'grid',
justifyItems: 'center',
width: '100%',
padding: '6px 0',
border: 0,
background: 'none',
color: isToday ? COLORS.red : 'inherit',
cursor: 'pointer',
}}
>
<small style={{ textTransform: 'uppercase' }}>{weekdayLabel}</small>
<span style={{ fontSize: 22, fontWeight: isToday ? 700 : 400 }}>
{dayNumber}
</span>
</button>
)}
renderHourLabel={({ hour }) => `${String(hour).padStart(2, '0')}h`}
/>
</div>
);
}
Themes
theme switches between light, dark and the system setting, and --rlc-* CSS variables
change colors, sizes and fonts.
import { useState, type CSSProperties } from 'react';
import Calendar, {
type CalendarTheme,
type CalendarView,
} from 'react-lightweight-calendar';
import { createEvents } from './data';
// A theme is `theme` ('light', 'dark' or 'auto') plus any --rlc-* variables.
// Set the variables with `style`, or in CSS on `.rlc` or any parent.
const PRESETS: Record<string, { theme: CalendarTheme; style?: CSSProperties }> =
{
Light: { theme: 'light' },
Dark: { theme: 'dark' },
Brand: {
theme: 'light',
style: {
'--rlc-primary': '#7c3aed',
'--rlc-event-bg': '#7c3aed',
'--rlc-border': '#e9e3f7',
'--rlc-radius': '16px',
} as CSSProperties,
},
Ocean: {
theme: 'dark',
style: {
'--rlc-bg': '#0b1e2d',
'--rlc-surface': '#12324a',
'--rlc-border': '#1d3f58',
'--rlc-primary': '#5eead4',
'--rlc-today-text': '#05231f',
'--rlc-event-bg': '#0f766e',
'--rlc-now-color': '#fbbf24',
} as CSSProperties,
},
Compact: {
theme: 'light',
style: {
'--rlc-font-size': '12px',
'--rlc-hour-height': '32px',
'--rlc-item-height': '18px',
} as CSSProperties,
},
};
export default function Theming() {
// Without `bgColor` on the items, they all use --rlc-event-bg.
const [events] = useState(() =>
createEvents().map(({ bgColor, ...event }) => event),
);
const [view, setView] = useState<CalendarView>('WEEK_TIME');
const [date, setDate] = useState<string | Date>(new Date());
const [preset, setPreset] = useState('Ocean');
return (
<>
<div
style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 12 }}
>
{Object.keys(PRESETS).map((name) => (
<button
key={name}
aria-pressed={name === preset}
onClick={() => setPreset(name)}
>
{name}
</button>
))}
</div>
<div style={{ height: 560 }}>
<Calendar
theme={PRESETS[preset].theme}
style={PRESETS[preset].style}
data={events}
activeTimeDateField="start-end"
currentView={view}
onViewChange={setView}
views={['MONTH', 'WEEK_TIME', 'DAY']}
currentDate={date}
setCurrentDate={setDate}
/>
</div>
</>
);
}
Languages
A date-fns locale translates month and weekday names,
labels the texts of the calendar, and the locale knows the first day of the week.
import type { Locale } from 'date-fns';
import { de, enUS, fr, ja, srLatn } from 'date-fns/locale';
import { useState } from 'react';
import Calendar, {
type CalendarLabels,
type CalendarView,
type TimeFormat,
} from 'react-lightweight-calendar';
import { createEvents } from './data';
interface Language {
name: string;
locale: Locale;
labels?: CalendarLabels;
formats?: TimeFormat;
}
const LANGUAGES: Language[] = [
{ name: 'English', locale: enUS },
{
name: 'Deutsch',
locale: de,
labels: {
today: 'Heute',
allDay: 'Ganztägig',
more: (count) => `+${count} weitere`,
views: { MONTH: 'Monat', WEEK_TIME: 'Woche', DAY: 'Tag' },
},
formats: { hour: 'HH:mm', time: 'HH:mm' },
},
{
name: 'Français',
locale: fr,
labels: {
today: "Aujourd'hui",
allDay: 'Journée',
more: (count) => `+${count} autres`,
views: { MONTH: 'Mois', WEEK_TIME: 'Semaine', DAY: 'Jour' },
},
formats: { hour: 'HH:mm', time: 'HH:mm' },
},
{
name: 'Srpski',
locale: srLatn,
labels: {
today: 'Danas',
allDay: 'Ceo dan',
more: (count) => `još ${count}`,
views: { MONTH: 'Mesec', WEEK_TIME: 'Nedelja', DAY: 'Dan' },
},
formats: { hour: 'HH:mm', time: 'HH:mm' },
},
{
name: '日本語',
locale: ja,
labels: {
today: '今日',
allDay: '終日',
views: { MONTH: '月', WEEK_TIME: '週', DAY: '日' },
},
formats: { hour: 'H時', time: 'H:mm' },
},
];
export default function Localization() {
const [events] = useState(createEvents);
const [view, setView] = useState<CalendarView>('WEEK_TIME');
const [date, setDate] = useState<string | Date>(new Date());
const [language, setLanguage] = useState(LANGUAGES[1]);
return (
<>
<select
aria-label="Language"
style={{ marginBottom: 12 }}
value={language.name}
onChange={(e) =>
setLanguage(LANGUAGES.find((l) => l.name === e.target.value)!)
}
>
{LANGUAGES.map((l) => (
<option key={l.name}>{l.name}</option>
))}
</select>
<div style={{ height: 560 }}>
<Calendar
data={events}
activeTimeDateField="start-end"
currentView={view}
onViewChange={setView}
views={['MONTH', 'WEEK_TIME', 'DAY']}
currentDate={date}
setCurrentDate={setDate}
// Month and weekday names, and the first day of the week.
locale={language.locale}
weekStartsOn={language.locale.options?.weekStartsOn ?? 1}
labels={language.labels}
timeDateFormat={language.formats}
/>
</div>
</>
);
}
Color dots
colorDots marks days next to their number, and the legend under the calendar lists
each color once.
import { addDays, startOfMonth } from 'date-fns';
import { useState } from 'react';
import Calendar, { toDateKey, type ColorDot } from 'react-lightweight-calendar';
import { COLORS, createEvents } from './data';
/** One dot per day. The legend under the calendar lists each color once. */
function createDots(): ColorDot[] {
const first = startOfMonth(new Date());
const day = (offset: number) => toDateKey(addDays(first, offset));
return [
{ color: COLORS.red, text: 'Deadline', date: day(11) },
{ color: COLORS.green, text: 'Public holiday', date: day(18) },
{ color: COLORS.yellow, text: 'On call', date: day(4) },
{ color: COLORS.yellow, text: 'On call', date: day(5) },
];
}
export default function ColorDots() {
const [events] = useState(createEvents);
const [dots] = useState(createDots);
const [date, setDate] = useState<string | Date>(new Date());
const [clicked, setClicked] = useState('');
return (
<>
<p style={{ margin: '0 0 12px' }}>
{clicked ||
'Click a dot next to a day number, or an entry in the legend.'}
</p>
<div style={{ height: 600 }}>
<Calendar
data={events}
activeTimeDateField="start-end"
currentView="MONTH"
currentDate={date}
setCurrentDate={setDate}
colorDots={dots}
onColorDotClick={(dot) => setClicked(`${dot.text} on ${dot.date}`)}
/>
</div>
</>
);
}
Collapsing cells
cellDisplayMode collapses cells to their last item: all of them, or the ones you list.
Click cells to collapse them.
import { useState } from 'react';
import Calendar, {
type CalendarView,
type CellDisplayModeState,
} from 'react-lightweight-calendar';
import { createEvents } from './data';
type State = `${CellDisplayModeState}`;
const STATES: State[] = ['CUSTOM', 'ALL_COLLAPSED', 'ALL_EXPANDED'];
export default function CollapsingCells() {
const [events] = useState(createEvents);
const [view, setView] = useState<CalendarView>('MONTH');
const [date, setDate] = useState<string | Date>(new Date());
const [state, setState] = useState<State>('CUSTOM');
// Collapsed cells: `yyyy-MM-dd`, or `yyyy-MM-dd HH:mm:ss` in the hour views.
const [inactiveCells, setInactiveCells] = useState<string[]>([]);
const toggle = (cell: string) =>
setInactiveCells((cells) =>
cells.includes(cell) ? cells.filter((c) => c !== cell) : [...cells, cell],
);
return (
<>
<div
style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 12 }}
>
{STATES.map((s) => (
<button
key={s}
aria-pressed={s === state}
onClick={() => setState(s)}
>
{s}
</button>
))}
</div>
<div style={{ height: 600 }}>
{/* A collapsed cell shows only its last item. */}
<Calendar
data={events}
activeTimeDateField="start-end"
currentView={view}
onViewChange={setView}
views={['MONTH', 'WEEK', 'WEEK_IN_PLACE']}
currentDate={date}
setCurrentDate={setDate}
cellDisplayMode={{ [view]: { state, inactiveCells } }}
onCellClick={({ timeDate }) => state === 'CUSTOM' && toggle(timeDate)}
/>
</div>
</>
);
}
Use cases
Booking calendar
Bookings are whole days, so their dates are yyyy-MM-dd values and they show as bars.
renderCellContent adds a price to the free days.
import { addDays, startOfMonth } from 'date-fns';
import { useState } from 'react';
import Calendar, { toDateKey } from 'react-lightweight-calendar';
interface Booking {
id: string;
title: string;
/** Check-in and check-out days, `yyyy-MM-dd`: both days are included. */
from: string;
to: string;
bgColor: string;
}
function createBookings(): Booking[] {
const first = startOfMonth(new Date());
const day = (offset: number) => toDateKey(addDays(first, offset));
return [
{
id: 'b1',
title: 'Smith family',
from: day(3),
to: day(7),
bgColor: '#009688',
},
{
id: 'b2',
title: 'J. Novak',
from: day(10),
to: day(12),
bgColor: '#3f51b5',
},
{
id: 'b3',
title: 'Conference group',
from: day(15),
to: day(21),
bgColor: '#f4511e',
},
{
id: 'b4',
title: 'Weekend guests',
from: day(25),
to: day(27),
bgColor: '#8e24aa',
},
];
}
const PRICES = [89, 99, 99, 109, 119, 149, 149];
export default function BookingCalendar() {
const [bookings] = useState(createBookings);
const [date, setDate] = useState<string | Date>(new Date());
const [selected, setSelected] = useState('');
return (
<>
<p style={{ margin: '0 0 12px' }}>
{selected
? `Selected night: ${selected}`
: 'Click a free day to pick a night.'}
</p>
<div style={{ height: 600 }}>
<Calendar<Booking>
data={bookings}
// Any field names work; date-only values make whole-day bars.
activeTimeDateField="from-to"
currentView="MONTH"
currentDate={date}
setCurrentDate={setDate}
onCellClick={({ date: day }) => setSelected(day)}
// Extra content in each day cell: the price of free days.
renderCellContent={({ date: day, items, isCurrentMonth }) =>
isCurrentMonth && items.length === 0 ? (
<span
style={{
position: 'absolute',
right: 6,
bottom: 4,
fontSize: 12,
fontWeight: 600,
color: '#33b679',
}}
>
€{PRICES[day.getDay()]}
</span>
) : null
}
/>
</div>
</>
);
}
Next.js App Router
Fetch on the server and render the calendar in a Client Component. It shows “today” and places items in the visitor’s time zone, so render it in the browser only.
import Schedule from './Schedule';
export default async function SchedulePage() {
const events = await getEvents(); // your data source
return <Schedule events={events} />;
}'use client';
import dynamic from 'next/dynamic';
import { useState } from 'react';
import type { CalendarItem, CalendarView } from 'react-lightweight-calendar';
const Calendar = dynamic(() => import('react-lightweight-calendar'), { ssr: false });
export default function Schedule({ events }: { events: CalendarItem[] }) {
const [view, setView] = useState<CalendarView>('WEEK_TIME');
const [date, setDate] = useState<string | Date>(new Date());
return (
<div style={{ height: 640 }}>
<Calendar
data={events}
activeTimeDateField="start-end"
currentView={view}
onViewChange={setView}
currentDate={date}
setCurrentDate={setDate}
/>
</div>
);
}