I am using FullCalendar in my React project, and I have an issue with the navigation buttons (prev()
and next()
) after clicking on a specific month.
Here’s a simplified version of my code:
const handleMonthClick = (monthIndex) => {
const calendarApi = calendarRef.current?.getApi();
const currentDate = calendarApi.getDate(); // Get the current date
let c_year = Number(moment(currentDate).format("YYYY"));
let c_month = Number(moment(currentDate).format("MM"));
if (calendarApi) {
// Navigate to the clicked month
const newDate = new Date(c_year, monthIndex, 1); // monthIndex is 0-based
calendarApi.gotoDate(newDate);
setSelectedMonth(monthIndex); // Set the selected month
setSelectedYear(c_year); // Set the selected year
}
};
const handleNavigation = (direction) => {
const calendarApi = calendarRef.current?.getApi();
const currentDate = calendarApi.getDate();
let c_year = Number(moment(currentDate).format("YYYY"));
let c_month = Number(moment(currentDate).format("MM"));
if (direction === "prev") {
c_month -= 1; // Decrease month for prev
if (c_month < 0) {
c_month = 11; // Wrap around to December
c_year -= 1; // Decrease the year
}
} else if (direction === "next") {
c_month += 1; // Increase month for next
if (c_month > 11) {
c_month = 0; // Wrap around to January
c_year += 1; // Increase the year
}
}
// Update state with the new year and month
setSelectedMonth(c_month);
setSelectedYear(c_year);
// Navigate to the updated month
const newDate = new Date(c_year, c_month, 1);
calendarApi.gotoDate(newDate);
};
Problem:
- When I click on a month using
handleMonthClick()
, the calendar correctly navigates to that month. - However, when I use the
prev()
ornext()
buttons after selecting a month, it sometimes shows the wrong month.- For example, after selecting February (month 1) and clicking “next”, the calendar might display March correctly, but if I click “prev”, it might show December instead of January.
What I’ve tried:
- I’ve tried adjusting the
selectedMonth
andselectedYear
states after each month change, but it doesn’t seem to affect the behavior of theprev()
andnext()
buttons. - I’m using
calendarApi.gotoDate()
to navigate to the selected month, but I’m unsure if this is properly synchronized with theprev()
andnext()
functions.
Question:
- How can I fix the issue so that the
prev()
andnext()
buttons correctly show the previous and next months after usinggotoDate()
to navigate to a specific month?
Any help would be greatly appreciated!