React Simple Calendar - JavaScript Exercise #18

React Simple Calendar - JavaScript Exercise #18

Build a React Calendar Component

ยท

5 min read

Overview

In this exercise, you will be creating a simple calendar application using React. The calendar will display the current month and allow the user to navigate to previous and next months.

Instructions

  1. Create a new component called Calendar that will be the parent component for the calendar application.

  2. Inside the Calendar component, create a state object that will hold the current date (use the Date object in JavaScript to get the current date).

  3. Render the current month and year at the top of the calendar.

  4. Create a function that will generate an array of days for the current month. Each day should have the following properties: date (the actual date), day (the day of the week), and events (an empty array that will hold any events for that day).

  5. Render the days of the month in a grid format using CSS Grid or Flexbox. Make sure to include the day of the week for each day.

  6. Add buttons to navigate to the previous and next months. Clicking on these buttons should update the state object and re-render the calendar with the appropriate month.

  7. Style the calendar using CSS.

Bonus Requirements

  1. Allow the user to add events to specific days by clicking on the day and filling out a form.

  2. Add animations to the calendar when the user navigates to a new month or clicks on a specific day.

  3. Add the ability to view events for the entire month in a separate view.

  4. Allow the user to filter events by type (e.g., work, personal, etc.).

  5. Allow the user to delete events from specific days.

Before you dive into the final output, I want to encourage you to take some time to work through the exercise yourself. I believe that active learning is the most effective way to learn and grow as a developer.

So, grab a pen and paper, fire up your code editor, and get ready to dive into the React Calendar exercise. Once you have completed the exercise, feel free to return to this blog post to compare your solution to mine.

Output for the Calendar exercise

import React, { useState } from 'react';
import './Calendar.css';

function Calendar() {
  // Set initial state
  const [date, setDate] = useState(new Date());

  // Function to generate an array of days for the current month
  function generateDays() {
    const daysInMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
    const days = [];
    for (let i = 1; i <= daysInMonth; i++) {
      const day = new Date(date.getFullYear(), date.getMonth(), i);
      days.push({
        date: day,
        dayOfWeek: day.toLocaleString('default', { weekday: 'short' }),
        events: []
      });
    }
    return days;
  }

  // Function to handle previous month button click
  function handlePrevMonth() {
    const newDate = new Date(date.getFullYear(), date.getMonth() - 1);
    setDate(newDate);
  }

  // Function to handle next month button click
  function handleNextMonth() {
    const newDate = new Date(date.getFullYear(), date.getMonth() + 1);
    setDate(newDate);
  }

  // Render calendar header with month and year
  const monthYear = date.toLocaleString('default', { month: 'long', year: 'numeric' });

  // Render days of the month using CSS Grid
  const days = generateDays();
  const calendarGrid = (
    <div className="calendar-grid">
      {days.map(day => (
        <div className="calendar-grid-cell" key={day.date}>
          <div className="calendar-grid-cell-header">{day.dayOfWeek}</div>
          <div className="calendar-grid-cell-body">{day.date.getDate()}</div>
        </div>
      ))}
    </div>
  );

  return (
    <div className="calendar">
      <div className="calendar-header">
        <button onClick={handlePrevMonth}>Previous Month</button>
        <div className="calendar-header-text">{monthYear}</div>
        <button onClick={handleNextMonth}>Next Month</button>
      </div>
      {calendarGrid}
    </div>
  );
}

export default Calendar;
.calendar {
  font-family: Arial, sans-serif;
  margin: 0 auto;
  max-width: 600px;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  background-color: #eee;
}

.calendar-header button {
  font-size: 1rem;
  padding: 0.5rem;
  border: none;
  background-color: #ddd;
  color: #333;
  cursor: pointer;
}

.calendar-header-text {
  font-size: 1.5rem;
  font-weight: bold;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  grid-gap: 0.5rem;
  padding: 1rem;
}

.calendar-grid-cell {
  display: flex;
  flex-direction: column;
  border: 1px solid #ddd;
  background-color: #fff;
}

.calendar-grid-cell-header {
  padding: 0.5rem;
  text-align: center;
}

.calendar-grid-cell-body {
  flex-grow: 1;
  padding: 0.5rem;
  text-align: center;
}

.calendar-grid-cell:hover {
  background-color: #f0f0f0;
}
import React from 'react';
import Calendar from './Calendar';

function App() {
  return (
    <div className="App">
      <Calendar />
    </div>
  );
}

export default App;

The Calendar component can be used in various applications where a user needs to view or interact with a calendar. Here are some examples:

  1. Scheduling app - a scheduling app can use the Calendar component to display available time slots and allow users to schedule appointments or meetings.

  2. Fitness app - a fitness app can use the Calendar component to display workout schedules or track progress for workouts completed.

  3. Booking app - a booking app can use the Calendar component to display availability of rooms or properties and allow users to book reservations.

  4. Education app - an education app can use the Calendar component to display class schedules or upcoming events such as exams, assignments, or school holidays.

  5. Project management app - a project management app can use the Calendar component to display deadlines or milestones and allow users to track progress and schedule tasks.

These are just a few examples of the many potential applications for the Calendar component. The component can be adapted and customized to fit the specific needs of any project that requires a calendar view.

The Calendar component is a simple yet powerful tool for displaying and interacting with dates in a user-friendly way. By using React and CSS, we can create a responsive and customizable calendar that can be used in a variety of applications. With the ability to handle different time zones, date formats, and events, the Calendar component can be adapted to fit the needs of any project. Whether it's for scheduling appointments, tracking workouts, or managing projects, the Calendar component can help users stay organized and on top of their schedules. By following best practices in React and CSS development, we can create a high-quality Calendar component that is both functional and visually appealing.

Thanks for taking this JavaScript exercise!

I hope you found this exercise helpful and enjoyable, and that it has deepened your understanding of React development. Keep practising and experimenting with React, and you'll be well on your way to becoming a skilled React developer!

If you have any questions or comments, feel free to reach out to me on Twitter(@rajeshtomjoe), or follow me for more updates.

And if you'd like to receive more exercise on JavaScript, be sure to subscribe to my blog.

ย