DatePicker Calendar in React

React DatePicker Calendar Component Explained (Month Navigation & Selection)

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.

This guide covers:
  • 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.

Each cell in the matrix is either:
  • 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 day
  • selectedDate → to highlight user selection

This logic keeps the UI responsive and intuitive.

Final Thoughts

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.

0 تعليقات

إرسال تعليق

Post a Comment (0)

أحدث أقدم