React DatePicker Calendar Component Explained (With Month Navigation)
A clean DatePicker is one of those components that looks simple on the surface, but underneath it requires careful handling of dates, months, selection state, and UI logic. In this article, we will break down a custom React DatePicker calendar component step by step.
- Calendar month navigation logic
- Date selection using
dayjs - Matrix-based calendar rendering
- Handling today & selected states
Component Overview
This DatePicker component uses a month matrix approach to render dates in a proper grid layout. It supports:
- Previous / Next month navigation
- Highlighting today’s date
- Persisting selected date
- External callback via
onDateSelect
State Management Explained
The component maintains three key pieces of state:
- currentMonth – Active month index
- currentYear – Active year
- selectedDate – Currently selected ISO date
Month Navigation Logic
Instead of manually calculating year boundaries, the component relies on the
JavaScript Date object to handle month overflow safely.
const changeMonth = (delta) => {
const newDate = new Date(currentYear, currentMonth + delta, 1);
setCurrentMonth(newDate.getMonth());
setCurrentYear(newDate.getFullYear());
};
Calendar Grid Rendering
The calendar layout is generated using a helper function
getMonthMatrix, which returns a two-dimensional array representing
weeks and days.
- A date object (valid day)
null(empty slot for alignment)
Date Selection Handling
const handleDateClick = (day) => {
const formattedDate = dayjs(
new Date(currentYear, currentMonth, day)
).format('YYYY-MM-DD');
setSelectedDate(formattedDate);
if (onDateSelect) {
onDateSelect(formattedDate);
}
};
This ensures:
- Consistent ISO date format
- Clean external communication
- Predictable UI updates
Today & Selected Date Highlighting
The component compares each rendered date against:
TODAY→ to mark the current dayselectedDate→ to highlight user selection
This logic keeps the UI responsive and intuitive.
📘 Recommended Reading:
How to Create a Calendar in JavaScript (Step-by-Step Guide)
This DatePicker component is modular, scalable, and production-ready. You can extend it with streaks, disabled dates, range selection, or API-driven data without changing the core logic.
Best Drawing Tablets for Students & Beginners
Ideal for online classes, note-taking, design & practice
XP-Pen Deco01 V3 (Large, Battery-Free) Wacom One CTL-672 (Medium, Reliable) Wacom One – Beginner Friendly XP-Pen StarG640 (Compact & Budget)As an Amazon Associate, I earn from qualifying purchases.