react-datepicker

repository·main·Indexed 27 days ago

https://github.com/hacker0x01/react-datepicker

A simple, reusable, and highly configurable date and time picker component for React applications. It supports keyboard navigation, internationalization via date-fns, and customizable time selection. The library provides a DatePicker component with extensive props for constraints, event handling, and Popper-based positioning, as well as helper components like CalendarContainer, CalendarIcon, and click_outside_wrapper.

Tokens
14K
Snippets
29
Records
92
Agent score
92%

What's inside react-datepicker

  1. Install react-datepicker

    main

    Install the package using npm or yarn. Note that react and prop-types must be installed separately as they are not included in the package. You must also import the component's CSS file for the picker to render correctly.

    npm install react-datepicker --save
    # or
    yarn add react-datepicker
  2. Handle UTC dates and server synchronization

    main

    When working with backends that store dates in UTC:

    1. Displaying UTC: Convert the UTC string from your server into a local Date object for the selected prop.
    2. Sending to Server: Use .toISOString() to send the date back as a UTC ISO string, or use .split('T')[0] to send a date-only string to avoid ambiguity.
    3. Avoiding Day Shifts: For date-only scenarios, create dates at noon local time (e.g., new Date(year, month, day, 12, 0, 0)) to prevent timezone boundaries from shifting the date when converted to UTC.
    // Convert UTC string to local Date for display
    const utcDateString = "2025-01-15T10:30:00Z";
    const date = new Date(utcDateString);
    
    // When sending back to server, convert to UTC ISO string
    const handleChange = (date) => {
      const utcString = date.toISOString(); 
      sendToServer(utcString);
    };
    
    <DatePicker selected={date} onChange={handleChange} />
  3. Localize the DatePicker

    main

    The library uses date-fns for internationalization. To use a locale other than the default en-US, you must import the locale from date-fns and register it using registerLocale.

    Locales can be applied to a specific instance via the locale prop or set globally using setDefaultLocale.

  4. Generate numeric ranges with lodash/range

    main

    Many examples use a range() function to generate arrays of numbers (e.g., for year dropdowns). You can install lodash to use its range function or implement a custom version.

    npm install lodash
    # or
    yarn add lodash
    import range from "lodash/range";
    
    const years = range(1990, 2030, 1); // [1990, 1991, ..., 2029]
  5. Solve the "Date is One Day Off" problem when converting to UTC

    main

    When a user selects a date, react-datepicker returns a Date object representing midnight in the local timezone. Calling .toISOString() on this object converts it to UTC, which can shift the date to the previous day if the local timezone is behind UTC.

    Choose a solution based on your needs:

    1. Date-only fields (Recommended): Extract the year, month, and day manually or use date-fns format to get a YYYY-MM-DD string.
    2. ISO string at local midnight: Adjust the date by the timezone offset before calling .toISOString().
    3. Localized string: Use .toLocaleDateString('en-CA') to get a YYYY-MM-DD format.
    4. Precise timestamps: Be aware of the UTC conversion implications for your backend.
    // Solution 1: Use date-fns format (Recommended for date-only)
    import { format } from "date-fns";
    
    const handleChange = (date) => {
      const dateString = format(date, "yyyy-MM-dd"); 
      sendToServer(dateString);
    };
    
    // Solution 2: Adjust for Timezone Offset (For ISO string at local midnight)
    const handleChange = (date) => {
      const offsetDate = new Date(date.getTime() - date.getTimezoneOffset() * 60000);
      const isoString = offsetDate.toISOString(); 
      sendToServer(isoString);
    };
  6. Localize react-datepicker

    main

    To use a locale other than English, register the locale using registerLocale from react-datepicker and provide a locale object from date-fns/locale. You can then apply it to a specific DatePicker instance via the locale prop or set it globally using setDefaultLocale.

    import { registerLocale, setDefaultLocale } from "react-datepicker";
    import { es } from "date-fns/locale/es";
    import { fr } from "date-fns/locale/fr";
    import { de } from "date-fns/locale/de";
    
    registerLocale("es", es);
    registerLocale("fr", fr);
    registerLocale("de", de);
    
    // Use in component
    <DatePicker locale="es" selected={date} onChange={setDate} />;
    
    // Or set globally
    setDefaultLocale("es");
  7. Basic Setup for react-datepicker

    main

    To implement react-datepicker, you must import the component and its required CSS. You can use the standard CSS file or CSS Modules depending on your project configuration.

    import React, { useState } from "react";
    import DatePicker from "react-datepicker";
    import "react-datepicker/dist/react-datepicker.css";
  8. Handle timezones with the timeZone prop

    main

    The timeZone prop allows you to specify an IANA timezone identifier (e.g., "America/New_York", "UTC", "Europe/London"). When set, the datepicker will display dates/times in this timezone and the onChange callback will return dates adjusted to this timezone.

    Note: This requires the date-fns-tz peer dependency to be installed:

    npm install date-fns-tz
    <DatePicker
      timeZone="America/New_York"
      selected={selectedDate}
      onChange={(date) => setSelectedDate(date)}
    />
  9. Configure DatePicker for multiple date selection

    main
    To allow selecting multiple individual dates, set selectsMultiple to true. The onChange callback will return an array of all selected dates (Date[] | null). You can use formatMultipleDates to define how this array of dates should be formatted into a string for the input field.