0

Is there way to set DayPickerRangeController custom visible month after component rendered? I have 'handleMonthChange' function which I want to change visible month when this function is called. I try to set 'initialVisible' month but it is not working.

import { useState } from "react";
import moment from "moment";
import { DayPickerRangeController } from "react-dates";
import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";

const Date = (props) => {
  const [startDate, setStartDate] = useState(null);
  const [endDate, setEndDate] = useState(null);
  const [focusedInput, setFocusedInput] = useState("startDate");
  const [initialMonth, setInitialMonth] = useState(moment("01-01-2021"));

  const handleDatesChange = ({ startDate, endDate }) => {
    setStartDate(moment(startDate, "MMM DD, YYYY"));
    setEndDate(moment(endDate, "MMM DD, YYYY"));
  };

  const handleMonthChange = () => {
    console.log("month change");
    setInitialMonth(moment("01-06-2021"));
  };
  return (
    <div>
      <DayPickerRangeController
        onDatesChange={handleDatesChange}
        focusedInput={focusedInput}
        startDate={startDate}
        endDate={endDate}
        numberOfMonths={2}
        initialVisibleMonth={() => initialMonth}
      />
      <button onClick={handleMonthChange}>Change Visible Month</button>
    </div>
  );
};

export default Date;
Aliaga Aliyev
  • 415
  • 1
  • 6
  • 22

1 Answers1

2

I found workaround solution. Unmounting component and then render with new initialMonth

import { useState } from "react";
import moment from "moment";
import { DayPickerRangeController } from "react-dates";
import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";

const Date = (props) => {
  const [startDate, setStartDate] = useState(null);
  const [endDate, setEndDate] = useState(null);
  const [focusedInput, setFocusedInput] = useState("startDate");
  const [initialMonth, setInitialMonth] = useState(moment("01-01-2021"));

  const handleDatesChange = ({ startDate, endDate }) => {
    setStartDate(moment(startDate, "MMM DD, YYYY"));
    setEndDate(moment(endDate, "MMM DD, YYYY"));
  };

  const handleMonthChange = () => {
    setInitialMonth(null)
    setTimeout(() => setInitialMonth(moment("01-06-2021")), 0);
  };

  if(!initialMonth) return <div>Loading...</div>

  return (
    <div>
      <DayPickerRangeController
        onDatesChange={handleDatesChange}
        focusedInput={focusedInput}
        startDate={startDate}
        endDate={endDate}
        numberOfMonths={2}
        initialVisibleMonth={() => initialMonth}
      />
      <button onClick={handleMonthChange}>Change Visible Month</button>
    </div>
  );
};

export default Date;
Aliaga Aliyev
  • 415
  • 1
  • 6
  • 22