I am currently able to fetch the given days of the current month as well as previous and future months using JS. What I would like to achieve, is if say December starts on a Tuesday I would like to pass in empty objects for Sunday and Monday. December also ends on a Thursday, so I would like to pass in empty objects for Friday and Saturday.
The code I am currently using to fetch each calendar month and display them is as follows:
import React, { useState, useEffect } from "react";
import "./styles.scss";
import dayjs from "dayjs";
export default function App() {
const [dates, setDates] = useState(null);
const [inc, setIncrement] = useState(0);
const getDaysArray = async (firstDay, lastDay) => {
let dates = [];
while (firstDay <= lastDay) {
dates.push(firstDay);
firstDay = dayjs(firstDay).add(1, "days").format("YYYY-MM-DD");
}
return dates;
};
useEffect(() => {
const getInitial = async () => {
const firstDay = dayjs().startOf("month").format("YYYY-MM-DD");
const lastDay = dayjs(firstDay).endOf("month").format("YYYY-MM-DD");
const dates = await getDaysArray(firstDay, lastDay);
setDates(dates);
};
getInitial();
}, []);
const fetchMonth = async (inc) => {
setIncrement(inc);
const firstDay = dayjs()
.subtract(inc, "months")
.startOf("month")
.format("YYYY-MM-DD");
const lastDay = dayjs(firstDay).endOf("month").format("YYYY-MM-DD");
const dates = await getDaysArray(firstDay, lastDay);
setDates(dates);
};
return (
<>
<button onClick={() => fetchMonth(inc + 1)}>DECREMENT</button>
<button onClick={() => fetchMonth(inc - 1)}>INCREMENT</button>
<div className="cal">
<div className="cal-div1"></div>
<div className="cal-div2 "></div>
<div className="cal-div3 cal-cir-hov"></div>
<div className="cal-div4"> SUN </div>
<div className="cal-div5"> MON </div>
<div className="cal-div6"> TUE </div>
<div className="cal-div7"> WED </div>
<div className="cal-div8"> THU </div>
<div className="cal-div9"> FRI </div>
<div className="cal-div10"> SAT </div>
{dates &&
dates.map((r, i) => {
return (
<div style={{ color: "#565254" }} key={i} className="cal-cir-hov">
{r}
</div>
);
})}
</div>
</>
);
}
the reason I am attempting to do so is due to the grid I have created. As it stands now, every month starts at sunday and I am not successfully pairing the correct days of the month with the days on the calendar. For example december starts on a tuesday, yet my styling shows it starts on a sunday any help would be greatly appreciated. the console logs currently show the days each month should start and end on.
I am unsure of how to push empty strings into my array for the days that should be empty on my calendar.
attached is a code pen for debugging : https://codesandbox.io/s/intelligent-cartwright-dm8go?file=/src/App.js:0-2006
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…