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: https://i.sstatic.net/4kBKpdLj.png

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

Is it possible to incorporate npm modules into a browser and utilize them locally on a personal computer?

This is my first time working with npm modules and node.js, so I find it quite challenging. I have a JavaScript code with multiple data points and I need to find the closest city to each of them. In response to another question on Stack Overflow (Reverse ...

Guide to refreshing the modal component with updated properties

In my application, I have created a modal component for managing recipes. This modal allows users to save recipes to a list. let modal = <Modal saveRecipe={this.saveRecipe} closeModal={this.toggleModal}/> However, I also want to utilize the same m ...

Having trouble importing cubing.js into my discord bot running on node

When attempting to import the cubing.js module into my nodejs project for use in a discord.js bot, I encountered an error. The specific import causing issues was const {randomScrambleForEvent } = require('cubing/scramble'), resulting in 'Err ...

Issue with sending functions to other components in Angular

I'm currently facing an issue with passing functions to other objects in Angular. Specifically, I've developed a function generateTile(coords) that fills a tile to be used by leaflet. This function is located within a method in the MapComponent. ...

Tips for setting up a listener for when the month changes in an ion-datetime object

When the user selects a different month, I need to update the highlightedDates by calling a query to retrieve all the dates of that specific month. This currently works if the user manually chooses a month and year using the top button, but not when they c ...

GitHub Pages allows users to create and host two separate websites from two distinct branches within a single repository

Here are the branches in my GitHub repository: main (only a README.md file) branch1 - NextJS project with deployable workflow to GitHub Pages. branch2 - static HTML website. I want branch1 at using GitHub Actions, and branch2 at as a static site. How ...

Unable to begin the previous project on my Mac, but it functions properly on Windows

After running npm i, I encountered the following error message which I am unsure how to resolve. I tried reinstalling Node.js, Python, and Pyenv, but the issue persists. Interestingly, the same version of Node.js on Windows runs the project without any p ...

Tips for managing the sub query in nodejs?

Developed a RESTful API in nodeJS focusing on a Post-type feature. The process involves executing two queries: 1. Initially fetching user-Id and answer details from the answers table. Upon checking the console, two user-Ids are displayed. 2. Secondly, que ...

Recursive function: the process of storing numerous values in variables

There is a code snippet showcasing a recursive function designed to take a number, for example n=5, and produce an array counting down from n to 1 (i.e., [5,4,3,2,1]). The point of confusion arises just before the numbers/values of n are added to countArr ...

Guidance on editing list items individually using jQuery from separate input fields

Working with li presents some challenges for me. On my webpage, I have an input field that dynamically adds values to a list. However, the function to edit these values is not working properly. After editing an li element, it deletes all classes and span ...

Activate the places_changed event in Google Maps by clicking the submit button

I would like to activate my placed_changed function when a submit button is clicked. Here's what I have so far: I've set up a searchbox using google.maps.places.SearchBox, and when I press enter while the search box is in focus, it triggers the e ...

The usage of Arrow Functions within Object Literal Syntax

I can't seem to understand why an arrow function within an object literal is invoked with window as the context for this. Any insights on this would be greatly appreciated. var arrowObject = { name: 'arrowObject', printName: () => { ...

Dealing with Buffer data received from a NextJS backend API

In my NextJS application, one of the backend API routes returns a JSON object that includes a buffer. // The nodeConfiguration contains a buffer for the nodeId property res.status(200).json(nodeConfiguration); However, when trying to display the nodeId va ...

Content will be loaded only after the user clicks on the item

On my blog, I have a share button that displays different social media platforms when clicked. However, the page takes longer to load due to fetching data from multiple servers like Facebook and Twitter. Is there a way to use jQuery to make these buttons l ...

Storing a collection of images simultaneously in Firebase Storage and saving their URLs in a Firestore document using Firebase v9

I am currently working on a form that requires users to input data in order to generate a detailed city document. Additionally, users must upload multiple photos of the city as part of this process. Once the form is submitted, a new city document is create ...

Troubleshooting Path Alias Issues While Containerizing a NextJS 13 Application in Docker

After creating a new NextJS app with npx create-next-app@latest, I encountered an issue when trying to build a Docker image from it. The problem lies in resolving path aliases during the build step, which works fine on my local machine but fails when build ...

Cross-site communication with Ajax using both POST and GET requests

As a beginner in JavaScript, I'm facing challenges with implementing ajax POST and GET requests. While I can successfully do it using Google Postman as shown here https://i.sstatic.net/Cegxj.pnghttps://i.sstatic.net/ovJT0.png, the problem arises when ...

Retrieve key codes from inputs sharing the same class

My webpage contains multiple text inputs that all share the same class for various reasons. Currently, I am attempting to capture the ESC button press when an input is focused and alert whether the input has a value or not. However, this functionality on ...

The functionality of router.prefetch is not recognized, which is causing difficulties in verifying the submit function with React Testing Library

This is a test code for evaluating the functionality of a component. I am checking whether a form submit function is triggered or not. import React from 'react' import { render, screen, fireEvent } from '@testing-library/react' import & ...

Using the window.prompt function to send information to specific fields in a MySQL database is not functioning correctly. I am looking for assistance with this issue

Currently, I am attempting to send some data to a server that is MySQL-based. After running the code below, it seems like there are no errors showing up in the console. Can you please review this code and let me know if you spot any issues? I would really ...