gpbl / react-day-picker

DayPicker is a customizable date picker component for React. Add date pickers, calendars, and date inputs to your web applications.
https://daypicker.dev
MIT License
6.04k stars 727 forks source link

DayPicker resets to current month after date selection #2389

Closed DarXnake closed 1 month ago

DarXnake commented 2 months ago

Hi, and thanks for reviewing this bug report! :)

Code

import { useState } from "react";
import { DayPicker, DateRange } from "react-day-picker";
import "react-day-picker/style.css";

export default function App() {
  const [selectedPeriod, setSelectedPeriod] = useState<DateRange | undefined>();

  return (
    <DayPicker
      mode="range"
      startMonth={new Date("2024-07-01")}
      endMonth={new Date("2025-07-31")}
      onSelect={setSelectedPeriod}
    />
  );
}

Expected Behavior

When a date is selected, the DayPicker should remain on the month of the selected date.

Actual Behavior

In any selection mode (single, range, or multiple), if you set a startMonth or endMonth and trigger an onSelect that updates a React state, the DayPicker display will reset to the current month instead of remaining on the month where you selected a day.

Removing either startMonth and endMonth or onSelect resolves this issue.

Exemple

CodeSandbox

hwennnn commented 2 months ago

I have encountered this issue as well!

hwennnn commented 2 months ago

I have downgraded the library to v9.0.6 for now, and it works. It seems like #2343 or #2358 caused this issue.

lariane-guerra commented 1 month ago

It didn't work for me to revert the version. Could you take a look at my issue to see if you can help me?

https://github.com/gpbl/react-day-picker/issues/2402

rbansal27 commented 1 month ago

Reverting the version didn't help.

The issue that I am facing is, I have the date picker placed inside a popover and on selecting the date from month other than the current, popover gets closed and reopening it, opens the date picker with the current date in focus. Ideally the selected date / month should be in view.

Pilaton commented 1 month ago

You can make an additional state for month navigation

const [currentMonth, setCurrentMonth] = useState<Date | undefined>(new Date());

<DayPicker
  ...
  month={currentMonth}
  onMonthChange={setCurrentMonth}
/>
tresorama commented 2 weeks ago

As alternative It's possible to use defaultMonth instead of month, but it's required to use a React state that rerender the whole Calendar component on date change. In this way it's possible to avoid having a separate state for the month.

const [selectedDate, setSelectedDate] = useState(new Date());

<Calendar
  mode="single"
  selected={selectedDate}
  onSelect={setSelectedDate}
  defaultMonth={selectedDate} // NOTE ME
/>

So, if you are using react-hook-form you must use the <Controller /> API and not the register API.