react-calendar vs react-datepicker vs react-datetime vs react-day-picker
React 日期选择组件库深度对比与选型指南
react-calendarreact-datepickerreact-datetimereact-day-picker类似的npm包:

React 日期选择组件库深度对比与选型指南

react-calendar、react-datepicker、react-datetime 和 react-day-picker 都是 React 生态中流行的日期处理库,但它们的定位和实现方式截然不同。react-calendar 专注于提供可嵌入的日历视图组件,适合需要自定义日期选择逻辑的场景。react-datepicker 是经典的输入框弹窗选择器,支持时间选择,上手简单。react-datetime 提供日期和时间组合选择,但维护活跃度较低。react-day-picker 强调无障碍访问(Accessibility)和高度定制,适合对用户体验要求严格的项目。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
react-calendar03,788271 kB205 个月前MIT
react-datepicker08,3824.5 MB969 个月前MIT
react-datetime02,004291 kB1822 年前MIT
react-day-picker06,850987 kB114 个月前MIT

React 日期选择器库:架构、定制与交互对比

这四个库都解决了同一个问题:如何在 React 中让用户选择日期。但它们的实现思路不同,导致在定制能力、交互体验和維護成本上有很大差异。我们从架构师的角度,深入对比它们在真实工程中的表现。

🖱️ 交互模式:嵌入视图 vs 输入框弹窗

交互模式决定了组件如何融入你的页面布局。有的库默认是独立的日历视图,有的则是绑定在输入框上的弹窗。

react-calendar 默认是独立的日历视图,不绑定输入框。

  • 适合嵌入到面板、模态框或作为页面固定部分。
  • 需要自己管理输入框状态如果需要显示文本。
// react-calendar: 独立视图
import Calendar from 'react-calendar';

function MyCalendar() {
  const [value, onChange] = useState(new Date());
  return <Calendar onChange={onChange} value={value} />;
}

react-datepicker 默认是输入框绑定弹窗模式。

  • 点击输入框弹出日历,选择后关闭。
  • 符合传统表单交互习惯。
// react-datepicker: 输入框弹窗
import DatePicker from 'react-datepicker';

function MyDatePicker() {
  const [date, setDate] = useState(new Date());
  return <DatePicker selected={date} onChange={(d) => setDate(d)} />;
}

react-datetime 也是输入框绑定弹窗模式。

  • 类似 react-datepicker,但渲染结构不同。
  • 支持自定义输入框渲染。
// react-datetime: 输入框弹窗
import DateTime from 'react-datetime';

function MyDateTime() {
  const [date, setDate] = useState(new Date());
  return <DateTime value={date} onChange={setDate} />;
}

react-day-picker 默认是独立视图,但可配合输入框使用。

  • v8 版本后更灵活,可自由组合输入框。
  • 需要额外代码实现弹窗逻辑。
// react-day-picker: 独立视图(需自行组合弹窗)
import { DayPicker } from 'react-day-picker';

function MyDayPicker() {
  const [selected, setSelected] = useState(new Date());
  return <DayPicker mode="single" selected={selected} onSelect={setSelected} />;
}

🎨 样式定制:CSS 类名 vs 完全控制

在真实项目中,UI 设计稿往往与默认样式不符。定制能力决定了你需要写多少覆盖代码。

react-calendar 依赖特定的 CSS 类名。

  • 需要引入默认 CSS 文件,然后覆盖类名。
  • 类名层级较深,定制复杂样式较麻烦。
/* react-calendar: 覆盖类名 */
.react-calendar__tile--active {
  background: #006ed3;
}
// react-calendar: 使用 className  prop
<Calendar className="my-custom-calendar" />;

react-datepicker 同样依赖 CSS 类名覆盖。

  • 提供 SCSS 源文件,方便变量定制。
  • 弹窗位置可能需要调整 zIndex。
/* react-datepicker: 覆盖类名 */
.react-datepicker__day--selected {
  background-color: #216ba5;
}
// react-datepicker: 自定义类名
<DatePicker className="my-input" calendarClassName="my-calendar" />;

react-datetime 使用内联样式和类名混合。

  • 定制起来比较琐碎,需要针对多个子元素。
  • 社区提供的主题较少。
/* react-datetime: 覆盖类名 */
.rdtActive {
  background-color: #0094ff;
}
// react-datetime: 自定义输入框
<DateTime inputProps={{ className: 'my-input' }} />;

react-day-picker 提供 CSS 变量和类名,v8 支持更灵活的样式钩子。

  • 默认样式更现代,易于覆盖。
  • 支持通过 components 属性替换内部 DOM 结构。
/* react-day-picker: 使用 CSS 变量 */
.rdp-day_selected {
  background-color: var(--rdp-selected-bg);
}
// react-day-picker: 替换内部组件
<DayPicker components={{ Day: CustomDayComponent }} />;

📅 高级功能:范围选择与时间支持

业务场景往往不止选择单个日期,还需要范围选择(开始 - 结束)或具体时间。

react-calendar 原生支持范围选择。

  • 通过 selectRange 属性开启。
  • 返回值为数组 [start, end]。
// react-calendar: 范围选择
<Calendar 
  selectRange={true} 
  onChange={(range) => console.log(range)} 
/>;

react-datepicker 支持范围选择和时间选择。

  • 通过 selectsRange 和 showTimeSelect 开启。
  • 配置项丰富,但 props 较多。
// react-datepicker: 范围与时间
<DatePicker 
  selectsRange 
  showTimeSelect 
  startDate={startDate} 
  endDate={endDate} 
  onChange={(update) => setDates(update)} 
/>;

react-datetime 支持时间选择,范围选择需自定义。

  • 时间选择是其强项,配置简单。
  • 范围选择没有原生支持,需自行管理状态。
// react-datetime: 时间选择
<DateTime 
  dateFormat="YYYY-MM-DD" 
  timeFormat="HH:mm" 
  value={date} 
  onChange={setDate} 
/>;

react-day-picker 原生支持范围选择,时间需配合其他库。

  • v8 版本对范围选择支持很好。
  • 时间选择通常建议配合 react-timepicker 或原生 input。
// react-day-picker: 范围选择
<DayPicker 
  mode="range" 
  selected={range} 
  onSelect={setRange} 
/>;

♿ 无障碍与类型安全

对于企业级应用,无障碍访问(A11y)和 TypeScript 支持是硬性指标。

react-calendar 无障碍支持一般。

  • 键盘导航可用,但屏幕阅读器支持有限。
  • TypeScript 类型定义由社区维护。
// react-calendar: 类型定义
import { CalendarProps } from 'react-calendar';
// 类型可能不够精确

react-datepicker 无障碍支持较好。

  • 支持键盘导航和 ARIA 标签。
  • 内置 TypeScript 定义。
// react-datepicker: 类型定义
import { DatePickerProps } from 'react-datepicker';
// 类型覆盖较全

react-datetime 无障碍支持较弱。

  • 部分元素缺少 ARIA 属性。
  • 类型定义需额外安装或自行声明。
// react-datetime: 类型定义
import DateTime from 'react-datetime';
// 可能需要 @types/react-datetime

react-day-picker 无障碍支持最佳。

  • 完全遵循 WAI-ARIA 标准。
  • 原生 TypeScript 支持,类型推导友好。
// react-day-picker: 类型定义
import { DayPickerProps } from 'react-day-picker';
// 类型非常精确

🤝 共同点:共享的基础能力

尽管实现不同,它们都解决了一些核心问题。

1. 📅 日期格式化与解析

  • 都依赖外部库(如 date-fns 或 moment)或内置简单格式化。
  • react-datepicker 和 react-datetime 内置较多格式化选项。
// 通用:处理日期对象
const date = new Date();
// 所有库都接受 Date 对象作为 value

2. 🌍 国际化支持

  • 都支持通过配置切换语言。
  • react-day-picker 和 react-calendar 依赖 date-fns 本地化。
// 通用:设置语言
// react-day-picker
<DayPicker locale="zh-CN" />
// react-datepicker
<DatePicker locale="zh-CN" />

3. 🚫 禁用日期逻辑

  • 都提供回调函数来禁用特定日期(如周末、过去日期)。
// 通用:禁用逻辑
// react-calendar
<Calendar minDate={new Date()} />
// react-datepicker
<DatePicker minDate={new Date()} />
// react-day-picker
<DayPicker disabled={{ before: new Date() }} />

📊 总结表

特性react-calendarreact-datepickerreact-datetimereact-day-picker
默认交互嵌入视图输入框弹窗输入框弹窗嵌入视图
范围选择✅ 原生支持✅ 原生支持❌ 需自定义✅ 原生支持
时间选择❌ 不支持✅ 原生支持✅ 原生支持❌ 需配合其他库
样式定制CSS 覆盖CSS 覆盖CSS 覆盖CSS 变量 + 组件替换
无障碍⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️
TS 支持社区定义内置社区定义原生内置
维护状态活跃活跃较少更新非常活跃

💡 最终建议

react-calendar 适合需要灵活嵌入日历视图的场景 — 比如 dashboard 上的小日历。如果你需要范围选择但不需要时间,它是轻量级的好选择。

react-datepicker 是传统表单的最佳拍档 — 尤其是需要时间选择的后台系统。它的文档最多,遇到问题容易找到解决方案。

react-datetime 建议仅在维护旧项目时使用 — 新项目面临维护风险和无障碍挑战。如果必须用,请做好自行修复 Bug 的准备。

react-day-picker 是现代 React 应用的首选 — 尤其是对无障碍和类型安全有要求的项目。虽然配置弹窗需要多一点代码,但长期维护成本最低。

核心原则:不要为了省几行代码而牺牲用户体验。如果项目周期长,react-day-picker 的架构优势会更明显;如果追求快速交付且需要时间选择,react-datepicker 更稳妥。

如何选择: react-calendar vs react-datepicker vs react-datetime vs react-day-picker

  • react-calendar:

    选择 react-calendar 如果你需要嵌入式的日历视图,而不是传统的输入框弹窗。它非常适合构建自定义的日期范围选择器,或者需要将日历作为页面布局一部分的场景。它的 API 简单,但样式定制需要覆盖较多 CSS 类名。

  • react-datepicker:

    选择 react-datepicker 如果你需要传统的输入框点击弹出日历的交互,且必须支持时间选择。它是迁移自 jQuery datepicker 用户的常见选择,生态成熟,文档丰富,适合快速落地的后台管理系统。

  • react-datetime:

    选择 react-datetime 仅适用于维护旧项目。对于新项目,由于其维护活跃度不如其他库且无障碍支持较弱,建议评估 react-datepicker 或 react-day-picker 作为替代。它在处理 React 新版本特性时可能需要额外配置。

  • react-day-picker:

    选择 react-day-picker 如果你对无障碍访问(A11y)有严格要求,或者需要高度定制日历的渲染逻辑。它支持 TypeScript 类型定义最好,且 v8 版本后更加灵活,适合设计系统或复杂的企业级应用。

react-calendar的README

npm downloads CI

react-calendar

Ultimate calendar for your React app.

  • Pick days, months, years, or even decades
  • Supports range selection
  • Supports virtually any language
  • No moment.js needed

tl;dr

  • Install by executing npm install react-calendar or yarn add react-calendar.
  • Import by adding import Calendar from 'react-calendar'.
  • Use by adding <Calendar />. Use onChange prop for getting new values.

Demo

A minimal demo page can be found in sample directory.

Online demo is also available!

Before you continue

react-calendar is under constant development. This documentation is written for react-calendar 4.x branch. If you want to see documentation for other versions of react-calendar, use dropdown on top of GitHub page to switch to an appropriate tag. Here are quick links to the newest docs from each branch:

Getting started

Compatibility

Your project needs to use React 16.8 or later.

react-calendar uses modern web technologies. That's why it's so fast, lightweight and easy to style. This, however, comes at a cost of supporting only modern browsers.

My locale isn't supported! What can I do?

If your locale isn't supported, you can use Intl.js or another Intl polyfill along with react-calendar.

Installation

Add react-calendar to your project by executing npm install react-calendar or yarn add react-calendar.

Usage

Here's an example of basic usage:

import { useState } from 'react';
import Calendar from 'react-calendar';

type ValuePiece = Date | null;

type Value = ValuePiece | [ValuePiece, ValuePiece];

function MyApp() {
  const [value, onChange] = useState<Value>(new Date());

  return (
    <div>
      <Calendar onChange={onChange} value={value} />
    </div>
  );
}

Check the sample directory in this repository for a full working example. For more examples and more advanced use cases, check Recipes in react-calendar Wiki.

Custom styling

If you want to use default react-calendar styling to build upon it, you can import react-calendar's styles by using:

import 'react-calendar/dist/Calendar.css';

User guide

Calendar

Displays a complete, interactive calendar.

Props

Prop nameDescriptionDefault valueExample values
activeStartDateThe beginning of a period that shall be displayed. If you wish to use react-calendar in an uncontrolled way, use defaultActiveStartDate instead.(today)new Date(2017, 0, 1)
allowPartialRangeWhether to call onChange with only partial result given selectRange prop.falsetrue
calendarTypeType of calendar that should be used. Can be 'gregory, 'hebrew', 'islamic', 'iso8601'. Setting to "gregory" or "hebrew" will change the first day of the week to Sunday. Setting to "islamic" will change the first day of the week to Saturday. Setting to "islamic" or "hebrew" will make weekends appear on Friday to Saturday.Type of calendar most commonly used in a given locale'iso8601'
classNameClass name(s) that will be added along with "react-calendar" to the main react-calendar <div> element.n/a
  • String: "class1 class2"
  • Array of strings: ["class1", "class2 class3"]
data-testidThe test ID used for testing purposes.n/a'calendar'
defaultActiveStartDateThe beginning of a period that shall be displayed by default. If you wish to use react-calendar in a controlled way, use activeStartDate instead.(today)new Date(2017, 0, 1)
defaultValueCalendar value that shall be selected initially. Can be either one value or an array of two values. If you wish to use react-calendar in a controlled way, use value instead.n/a
  • Date: new Date()
  • An array of dates: [new Date(2017, 0, 1), new Date(2017, 7, 1)]
defaultViewDetermines which calendar view shall be opened initially. Does not disable navigation. Can be "month", "year", "decade" or "century". If you wish to use react-calendar in a controlled way, use view instead.The most detailed view allowed"year"
formatDayFunction called to override default formatting of day tile labels. Can be used to use your own formatting function.(default formatter)(locale, date) => formatDate(date, 'd')
formatLongDateFunction called to override default formatting of day tile abbr labels. Can be used to use your own formatting function.(default formatter)(locale, date) => formatDate(date, 'dd MMM YYYY')
formatMonthFunction called to override default formatting of month names. Can be used to use your own formatting function.(default formatter)(locale, date) => formatDate(date, 'MMM')
formatMonthYearFunction called to override default formatting of months and years. Can be used to use your own formatting function.(default formatter)(locale, date) => formatDate(date, 'MMMM YYYY')
formatShortWeekdayFunction called to override default formatting of weekday names (shortened). Can be used to use your own formatting function.(default formatter)(locale, date) => formatDate(date, 'dd')
formatWeekdayFunction called to override default formatting of weekday names. Can be used to use your own formatting function.(default formatter)(locale, date) => formatDate(date, 'dd')
formatYearFunction called to override default formatting of year in the top navigation section. Can be used to use your own formatting function.(default formatter)(locale, date) => formatDate(date, 'YYYY')
goToRangeStartOnSelectWhether to go to the beginning of the range when selecting the end of the range.truefalse
inputRefA prop that behaves like ref, but it's passed to main <div> rendered by <Calendar> component.n/a
  • Function:
    (ref) => { this.myCalendar = ref; }
  • Ref created using createRef:
    this.ref = createRef();
    …
    inputRef={this.ref}
  • Ref created using useRef:
    const ref = useRef();
    …
    inputRef={ref}
localeLocale that should be used by the calendar. Can be any IETF language tag. Note: When using SSR, setting this prop may help resolving hydration errors caused by locale mismatch between server and client.Server locale/User's browser settings"hu-HU"
maxDateMaximum date that the user can select. Periods partially overlapped by maxDate will also be selectable, although react-calendar will ensure that no later date is selected.n/aDate: new Date()
maxDetailThe most detailed view that the user shall see. View defined here also becomes the one on which clicking an item will select a date and pass it to onChange. Can be "month", "year", "decade" or "century"."month""year"
minDateMinimum date that the user can select. Periods partially overlapped by minDate will also be selectable, although react-calendar will ensure that no earlier date is selected.n/aDate: new Date()
minDetailThe least detailed view that the user shall see. Can be "month", "year", "decade" or "century"."century""decade"
navigationAriaLabelaria-label attribute of a label rendered on calendar navigation bar.n/a"Go up"
navigationAriaLivearia-live attribute of a label rendered on calendar navigation bar.undefined"polite"
navigationLabelContent of a label rendered on calendar navigation bar.(default label)({ date, label, locale, view }) => alert(`Current view: ${view}, date: ${date.toLocaleDateString(locale)}`)
next2AriaLabelaria-label attribute of the "next on higher level" button on the navigation pane.n/a"Jump forwards"
next2LabelContent of the "next on higher level" button on the navigation pane. Setting the value explicitly to null will hide the icon."»"
  • String: "»"
  • React element: <DoubleNextIcon />
nextAriaLabelaria-label attribute of the "next" button on the navigation pane.n/a"Next"
nextLabelContent of the "next" button on the navigation pane. Setting the value explicitly to null will hide the icon."›"
  • String: "›"
  • React element: <NextIcon />
onActiveStartDateChangeFunction called when the user navigates from one view to another using previous/next button. Note that this function will not be called when e.g. drilling up from January 2021 to 2021 or drilling down the other way around.
action signifies the reason for active start date change and can be one of the following values: "prev", "prev2", "next", "next2", "drillUp", "drillDown", "onChange".
n/a({ action, activeStartDate, value, view }) => alert('Changed view to: ', activeStartDate, view)
onChangeFunction called when the user clicks an item (day on month view, month on year view and so on) on the most detailed view available.n/a(value, event) => alert('New date is: ', value)
onClickDayFunction called when the user clicks a day.n/a(value, event) => alert('Clicked day: ', value)
onClickDecadeFunction called when the user clicks a decade.n/a(value, event) => alert('Clicked decade: ', value)
onClickMonthFunction called when the user clicks a month.n/a(value, event) => alert('Clicked month: ', value)
onClickWeekNumberFunction called when the user clicks a week number.n/a(weekNumber, date, event) => alert('Clicked week: ', weekNumber, 'that starts on: ', date)
onClickYearFunction called when the user clicks a year.n/a(value, event) => alert('Clicked year: ', value)
onDrillDownFunction called when the user drills down by clicking a tile.n/a({ activeStartDate, view }) => alert('Drilled down to: ', activeStartDate, view)
onDrillUpFunction called when the user drills up by clicking drill up button.n/a({ activeStartDate, view }) => alert('Drilled up to: ', activeStartDate, view)
onViewChangeFunction called when the user navigates from one view to another using drill up button or by clicking a tile.
action signifies the reason for view change and can be one of the following values: "prev", "prev2", "next", "next2", "drillUp", "drillDown", "onChange".
n/a({ action, activeStartDate, value, view }) => alert('New view is: ', view)
prev2AriaLabelaria-label attribute of the "previous on higher level" button on the navigation pane.n/a"Jump backwards"
prev2LabelContent of the "previous on higher level" button on the navigation pane. Setting the value explicitly to null will hide the icon."«"
  • String: "«"
  • React element: <DoublePreviousIcon />
prevAriaLabelaria-label attribute of the "previous" button on the navigation pane.n/a"Previous"
prevLabelContent of the "previous" button on the navigation pane. Setting the value explicitly to null will hide the icon."‹"
  • String: "‹"
  • React element: <PreviousIcon />
returnValueWhich dates shall be passed by the calendar to the onChange function and onClick{Period} functions. Can be "start", "end" or "range". The latter will cause an array with start and end values to be passed."start""range"
selectRangeWhether the user shall select two dates forming a range instead of just one. Note: This feature will make react-calendar return array with two dates regardless of returnValue setting.falsetrue
showDoubleViewWhether to show two months/years/… at a time instead of one. Defaults showFixedNumberOfWeeks prop to be true.falsetrue
showFixedNumberOfWeeksWhether to always show fixed number of weeks (6). Forces showNeighboringMonth prop to be true.falsetrue
showNavigationWhether a navigation bar with arrows and title shall be rendered.truefalse
showNeighboringCenturyWhether decades from next century shall be rendered to fill the entire last row in.falsetrue
showNeighboringDecadeWhether years from next decade shall be rendered to fill the entire last row in.falsetrue
showNeighboringMonthWhether days from previous or next month shall be rendered if the month doesn't start on the first day of the week or doesn't end on the last day of the week, respectively.truefalse
showWeekNumbersWhether week numbers shall be shown at the left of MonthView or not.falsetrue
tileClassNameClass name(s) that will be applied to a given calendar item (day on month view, month on year view and so on).n/a
  • String: "class1 class2"
  • Array of strings: ["class1", "class2 class3"]
  • Function: ({ activeStartDate, date, view }) => view === 'month' && date.getDay() === 3 ? 'wednesday' : null
tileContentAllows to render custom content within a given calendar item (day on month view, month on year view and so on).n/a
  • String: "Sample"
  • React element: <TileContent />
  • Function: ({ activeStartDate, date, view }) => view === 'month' && date.getDay() === 0 ? <p>It's Sunday!</p> : null
tileDisabledPass a function to determine if a certain day should be displayed as disabled.n/a({ activeStartDate, date, view }) => date.getDay() === 0
valueCalendar value. Can be either one value or an array of two values. If you wish to use react-calendar in an uncontrolled way, use defaultValue instead.n/a
  • Date: new Date()
  • String: 2017-01-01
  • An array of dates: [new Date(2017, 0, 1), new Date(2017, 7, 1)]
  • An array of strings: ['2017-01-01', '2017-08-01']
viewDetermines which calendar view shall be opened. Does not disable navigation. Can be "month", "year", "decade" or "century". If you wish to use react-calendar in an uncontrolled way, use defaultView instead.The most detailed view allowed"year"

MonthView, YearView, DecadeView, CenturyView

Displays a given month, year, decade and a century, respectively.

Props

Prop nameDescriptionDefault valueExample values
activeStartDateThe beginning of a period that shall be displayed.n/anew Date(2017, 0, 1)
hoverThe date over which the user is hovering. Used only when selectRange is enabled, to render a “WIP” range when the user is selecting range.n/anew Date(2017, 0, 1)
maxDateMaximum date that the user can select. Periods partially overlapped by maxDate will also be selectable, although react-calendar will ensure that no later date is selected.n/aDate: new Date()
minDateMinimum date that the user can select. Periods partially overlapped by minDate will also be selectable, although react-calendar will ensure that no earlier date is selected.n/aDate: new Date()
onClickFunction called when the user clicks an item (day on month view, month on year view and so on).n/a(value) => alert('New date is: ', value)
tileClassNameClass name(s) that will be applied to a given calendar item (day on month view, month on year view and so on).n/a
  • String: "class1 class2"
  • Array of strings: ["class1", "class2 class3"]
  • Function: ({ date, view }) => view === 'month' && date.getDay() === 3 ? 'wednesday' : null
tileContentAllows to render custom content within a given item (day on month view, month on year view and so on). Note: For tiles with custom content you might want to set fixed height of react-calendar__tile to ensure consistent layout.n/a({ date, view }) => view === 'month' && date.getDay() === 0 ? <p>It's Sunday!</p> : null
valueCalendar value. Can be either one value or an array of two values.n/a
  • Date: new Date()
  • An array of dates: [new Date(2017, 0, 1), new Date(2017, 7, 1)]
  • String: 2017-01-01
  • An array of strings: ['2017-01-01', '2017-08-01']

Useful links

License

The MIT License.

Author

Wojciech Maj Wojciech Maj

Thank you

Sponsors

Thank you to all our sponsors! Become a sponsor and get your image on our README on GitHub.

Backers

Thank you to all our backers! Become a backer and get your image on our README on GitHub.

Top Contributors

Thank you to all our contributors that helped on this project!

Top Contributors