Search code examples
reactjscss-griddayjs

CSS grid, Day.js : How do I create a calendar that shows the current week's dates?


Within a react component, I'd like to create a grid calendar showing showing the current week's dates. So for this week for example, it would need to look something like this:

Monday          | Tuesday         |Wednesday       |        
October 5th 2020| October 6th 2020|October 7th 2020|

I've had a play around with day.js to try and solve this, but it's proven tricky. Here's my attempt in codesanbox:

https://codesandbox.io/s/sleepy-rgb-me4s3?file=/src/App.js

Any suggestions on how to approach this? I'm not sure how to set the beginning of each grid to the monday of a given week - once I've done that, I can figure out the logic to do the other days.

Here's the code:

Grid component

import React from "react";
import "./styles.css";
import dayjs from 'dayjs'

export default App = () => {

  let now = dayjs()
  let currentDay = (now.format("dddd, MMMM D YYYY"))

  let d = now.add('1', 'day')
  let nextDay = (d.format("dddd, MMMM D YYYY"))
  
  return(
    <div className = 'grid-container'>
      <div className = 'grid-item'>{currentDay}</div>
      <div className = 'grid-item'>{nextDay}</div>
      <div className = 'grid-item'></div>
      <div className = 'grid-item'></div>
      <div className = 'grid-item'></div>
      <div className = 'grid-item'></div>
      <div className = 'grid-item'></div>
    </div>
  )
}

styles.css

.grid-container {
  display: grid;
  grid-template-rows: repeat(3, 100px);
  grid-row-gap:1px;
  grid-template-columns: 100px 100px 100px;
  grid-column-gap: 1px;
}

.grid-item {
  background-color: blue;
  color:white;
}

Solution

  • You can use startOf('week') to get the first day of the current week and then construct an array of all 7 days of that week to render it:

    export default () => {
      const startOfWeek = dayjs().startOf("week");
    
      const weekdays = new Array(7).fill(startOfWeek).map(
        (day, idx) => day.add(idx, "day").format("dddd, MMMM D YYYY")
      );
    
      return (
        <div className="grid-container">
          {weekdays.map((day) => (
            <div key={day} className="grid-item">
              {day}
            </div>
          ))}
        </div>
      );
    };
    

    Edit delicate-wind-mp1tg

    Depending on the locale the start of the week may vary. You can configure the start of a week to be monday by setting it in the locale:

    import en from "dayjs/locale/en";
    
    dayjs.locale({
      ...en,
      weekStart: 1
    });
    

    If you don't want to modify the locale you can also use day(1) to get the monday of the current week:

    const startOfWeek = dayjs().day(1); // will be the monday of the current week with the default locale