NextJS-created calendar does not begin on the correct day

I'm facing an issue with my calendar code where it starts rendering on a Wednesday instead of a Monday. I want to adjust the layout so that it always begins on a Monday by adding some empty boxes at the start of the calendar.

Essentially, I need to shift the Mon and Tue columns to the beginning and push the other days accordingly.

I attempted to use an if statement to check the starting day of the month and add empty divs, but it didn't achieve the desired effect (the calendar still starts on a Wednesday).

I'm unsure if my logic is flawed.

This is the current Calendar.tsx:

{(calSelection === "month" && currentCal && Object.keys(currentCal).length > 0) && 
Object.keys(currentCal).map(day => (
  <div key={day} className="w-[12vw] flex flex-col items-center">
    <p className="font-semibold w-[12vw]">{day}</p>
    <div>
      {currentCal[day] && currentCal[day].length > 0 && currentCal[day].map(date => (
      <p key={date.fullDate} className="w-[12vw] h-[14vh] border-[1px] border-[#9297B0]">{date.fullDate.split("T")[0].split("-")[2]}</p>
      ))}
    </div>
  </div>
))}

Here's the link to the screenshot for better understanding:

I've also tried this code snippet to insert empty boxes at the beginning, but it just shifts the entire calendar:

{Array.from({ length: moment().startOf('month').day() }).map((_, index) => (
  <div key={`empty-${index}`} className="w-[12vw] h-[14vh] border-[1px] border-transparent"></div>
))}

The calendar is pushed to the right with additional empty boxes.

Link to the code on GitHub: https://gist.github.com/imdarkk/b7e78f87fca82d8ec457e97537e515f9

Answer №1

Here's what I came up with as a solution: https://gist.github.com/imdarkk/8e5bc5f0c88200af8f3bc59d95bfb698 (Lines 17 through 37)

// Calculating the first day of the current month
            let firstDay = moment(curr.month, 'MMMM').startOf('month').isoWeekday(); // 0 for Sunday, 1 for Monday, 6 for Saturday

            // Checking if the first day is not Monday
            if (firstDay != 1) {
                let diff = firstDay - 1;
                const previousMonthName = moment(curr.month, "MMMM").subtract(1, 'month').format('MMMM');

                // Looping through days before the start of current month
                for(let i = 1; i < firstDay; i++) {
                    const previousMonthDays = acc[previousMonthName][moment().day(i).format('ddd')];
                    const lastItem = previousMonthDays[previousMonthDays.length - 1];

                    console.log('last item for ', curr.month, previousMonthName, moment().day(firstDay).format('ddd'), lastItem)
                    if(acc[curr.month][moment().day(i).format('ddd')].length == 0) {
                        acc[curr.month][moment().day(i).format('ddd')].push(lastItem)
                    }
                }
            }

The final implementation was done on the backend, but solutions for frontend are still welcomed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the most effective way to choose and give focus to an input using JavaScript or jQuery?

How do you use JavaScript or jQuery to focus on and select an input? This is the relevant snippet of my code: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> </he ...

Failure of Styling Inheritance in Angular 2 Child Components from Parent Components

My Parent Component utilizes a Child Component. I have defined the necessary styles in the Parent CSS file, and these styles change appropriately when hovering over the div. However, the Child Component does not inherit the styling classes of the Parent Co ...

"Pre-rendering in Next.js: Pages display content before redirecting

I seem to be encountering a problem with next.js when I click on navigation buttons that should redirect me to a new page. My navigation contains links similar to the one below: <button key={index}> <a href={ur ...

What is the best way to import a YAML file into a Vue project?

As a newcomer to Vue and the world of web development, I recently embarked on building a small app. In order to store data with comments, I opted to use YAML instead of JSON. I experimented with two different YAML parsers: https://github.com/nodeca/js-ya ...

Implementing Material-UI’s FlatButton and Dialog in ReactJS for dynamic TableRow functionality

I am working with Material-UI and have implemented a <Table> component. Each dynamically rendered <TableRow> in the <TableBody> needs to include a button (<FlatButton>) within one of the columns. When this button is clicked, a <D ...

What sets apart $document from $window.document in Angular?

After experimenting with the code on JSBin, I noticed that the first snippet successfully retrieved the canvas object, while the second one did not. JSBin: http://jsbin.com/natavejasa/1/edit?html,js,output var canvas = $window.document.getElementById(&ap ...

The NextJS application is experiencing issues with appending the API call correctly

Folder structure -Pages --Support ---StaffTable.js await axios.post('api/updateStaffDetails', { data: dataToSubmit }); Encountering an issue: Previously, I added a '/' in front of the API call to resolve it, but this time it's not ...

Display/Conceal JavaScript

I recently implemented a JavaScript function on my website to show/hide specific elements. However, being new to JavaScript, I have encountered some difficulties. I've spent quite some time troubleshooting the code but haven't been able to pinpoi ...

Error thrown by Jest: TypeError - req.headers.get function is not defined

I have a function that is used to find the header in the request object: export async function authorizeAccess(req: Request): Promise<Response | {}> { const access = req.headers.get('Access') if(!access) return Response.json('N ...

Having trouble getting the form to submit with jQuery's submitHandler

I am in the process of converting a contact form to AJAX so that I can utilize the success function. Currently, I am encountering an issue where the code is halting at the submitHandler section due to it being undefined. Can anyone identify why my submitHa ...

Navigate forward to the next available input in a grid by using the tab key

My goal is to improve form entry efficiency by using the tab key to focus on the next empty input field within a grid component. If an input field already has a value, it will be skipped. For example, if the cursor is in input field 2 and field 3 is filled ...

How can I prevent an HTML element from losing focus?

Currently, I am developing an online editor that requires accurate character inputs. To achieve this, I have implemented the jQuery.onKeyPress event on a textarea element. This approach was chosen because obtaining character inputs from the body directly p ...

Utilize angular to call a function when navigating

Having an issue with ChartJS while creating a chart using angular. The problem arises when navigating to a new page and then back to the original one, as the JavaScript is not triggered again. Is there a way to automatically invoke a JavaScript function o ...

What is the process for retrieving the address of the connected wallet using web3modal?

I've been working on an application using next.js and web3. In order to link the user's wallet to the front-end, I opted for web3modal with the following code: const Home: NextPage = () => { const [signer, setSigner] = useState<JsonRpcSig ...

Guide on utilizing the disable feature in SortableJS for a Vue project

I have successfully implemented the draggable effect on my el table using element-ui-el-table-draggable and it's working perfectly. Now, I am looking to incorporate the disable option from SortableJS, but I'm unsure how to integrate these two fu ...

Interactive Zoomable Tree with d3.js

I am looking to customize the zoomable icicle plot in d3js by incorporating my own data. Unfortunately, I am unable to locate the "readme.json" file for data modification and cannot get the graph to display on my local machine. Where can I find this elus ...

Why is my code executing twice rather than just once?

` import './App.css'; import ArrayState from './components/ArrayState'; import FetchApi from './components/FetchAPI/FetchApi'; import Login from './components/Login'; import Useeffect2 from './components/Use ...

Error in Express application due to uncaught SyntaxError

I am attempting to live stream data using websockets to Chartjs, however I keep encountering the following error. main.js:1 Uncaught SyntaxError: Unexpected token < What could be causing this issue? The code for my server and HTML is as follows: ...

pnpm may not be able to resolve dependencies

When I have my package.json file and install all dependencies with npm i, everything works fine. However, when I use pnpm i, I encounter an exception: TypeError: Cannot read property 'uid' of undefined. I don't actually use this library, so ...

Reacting to each change event, Angular dynamically loads new autocomplete options

I am facing an issue with my form where users need to select a company using mat-select-search. Upon selection, an API call is made with the selected company ID to fetch users from that company for the autocomplete feature in recipient fields. The process ...