Build a Calendar in React from Scratch
In today’s article, we’ll explore how to build a fully functional calendar component in React. Calendars are essential components in many applications, ranging from task managers to scheduling tools. By the end of this tutorial, you will have a deep understanding of how to handle dates in JavaScript, render them in React, and implement user interactions.
Table of Contents
- Getting Started
- Setting Up the Environment
- Project Structure
- Creating the Calendar Component
- Handling Navigation
- Implementing Date Selection
- Styling the Calendar
- Conclusion
Getting Started
Before we dive into coding, it’s important to ensure that you have a basic understanding of React and its concepts, such as components, props, and state management. In this tutorial, we’ll cover all the essential steps needed to create a calendar from scratch.
Setting Up the Environment
To start building our calendar, we need a React environment. You can quickly set it up using Create React App. If you haven’t installed Create React App yet, you can do it using the following command:
npx create-react-app my-calendar
Navigate into your new project folder:
cd my-calendar
Once you’re in the project directory, you can start your development server:
npm start
Your default browser should now open up with your new React app running.
Project Structure
For our calendar application, we’ll set up a simple project structure. You can create a folder named components in the src folder, where we will store our calendar component. The structure should look like this:
my-calendar/
├── src/
│ ├── components/
│ │ └── Calendar.js
│ └── App.js
...
Creating the Calendar Component
Let’s create the Calendar component. Open Calendar.js and add the following code:
import React, { useState } from 'react';
const Calendar = () => {
const [currentDate, setCurrentDate] = useState(new Date());
const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const getDaysInMonth = (month, year) => {
return new Date(year, month + 1, 0).getDate();
};
const getFirstDayOfMonth = (month, year) => {
return new Date(year, month, 1).getDay();
};
const renderCalendar = () => {
const daysInMonth = getDaysInMonth(currentDate.getMonth(), currentDate.getFullYear());
const firstDay = getFirstDayOfMonth(currentDate.getMonth(), currentDate.getFullYear());
const days = [];
for(let i = 0; i < firstDay; i++) {
days.push();
}
for(let day = 1; day <= daysInMonth; day++) {
days.push({day});
}
return days;
};
return (
{monthNames[currentDate.getMonth()]} {currentDate.getFullYear()}
{dayNames.map(day => {day})}
{renderCalendar()}
);
};
export default Calendar;
In this component:
- We’re using React’s useState hook to manage the current date.
- We defined two helper functions to get the number of days in a month and the starting day of the month.
- The renderCalendar function generates the calendar days dynamically.
Handling Navigation
Now that we have our calendar display set up, let’s add navigation to switch between months. We’ll add buttons to navigate to the previous and next months:
const handlePreviousMonth = () => {
setCurrentDate(new Date(currentDate.getFullYear(), currentDate.getMonth() - 1));
};
const handleNextMonth = () => {
setCurrentDate(new Date(currentDate.getFullYear(), currentDate.getMonth() + 1));
};
We’ll now update the return statement in our Calendar component to include these buttons:
return (
{monthNames[currentDate.getMonth()]} {currentDate.getFullYear()}
{dayNames.map(day => {day})}
{renderCalendar()}
);
Implementing Date Selection
Next, we want to allow users to select a date. To achieve this, we will modify the renderCalendar function to handle clicks on the days:
const handleDayClick = (day) => {
alert(`Selected date: ${day} ${monthNames[currentDate.getMonth()]} ${currentDate.getFullYear()}`);
};
...
days.push(
handleDayClick(day)}
>
{day}
);
Now, clicking a day will cause an alert to show the selected date.
Styling the Calendar
To make our calendar look visually appealing, let’s add some basic CSS. Create a new file named Calendar.css in the same components folder and import it into your Calendar.js component:
import './Calendar.css';
Now, add the following CSS styles to Calendar.css:
.calendar {
display: flex;
flex-direction: column;
align-items: center;
margin: 20px;
}
.header {
display: flex;
justify-content: space-between;
width: 100%;
}
.days {
display: grid;
grid-template-columns: repeat(7, 1fr);
gap: 5px;
margin-top: 10px;
}
.day, .day-name {
width: 40px;
height: 40px;
display: flex;
justify-content: center;
align-items: center;
border: 1px solid #ccc;
border-radius: 5px;
}
.day:hover {
background-color: #f0f0f0;
cursor: pointer;
}
Conclusion
Congratulations! You’ve now created a simple yet functional calendar component in React. You have learned how to:
- Set up a React environment using Create React App.
- Create a calendar component and manage its state.
- Implement month navigation and date selection.
- Style the calendar for a better user experience.
This project can serve as a foundation for more complex features, such as integrating it with external APIs, adding event handling, or even supporting drag-and-drop functionalities. The possibilities are endless!
Feel free to explore and expand on this basic implementation. Happy coding!
