Building a Calendar in React from Scratch
Creating a calendar application can be an excellent way to enhance your React skills. Not only does it help you understand date manipulation, but it also allows you to work on user interface design, component structuring, and state management. In this guide, we’ll walk through the process of building a simple, functional calendar from scratch using React.
Table of Contents
- Project Setup
- Creating the Calendar Component
- Implementing Date Navigation
- Adding Event Management
- Styling the Calendar
- Conclusion
Project Setup
First, you’ll need to set up a new React project. If you haven’t already, you can create a new React app using Create React App by running the following command:
npx create-react-app react-calendar
Once your project is created, navigate into your project directory:
cd react-calendar
Next, install the necessary dependencies for date manipulation. We’ll use date-fns:
npm install date-fns
Creating the Calendar Component
Now that we have our environment set up, let’s create a simple Calendar component. Create a new file named Calendar.js in the src directory and open it. Here’s a basic structure to get started:
import React, { useState } from 'react';
import { format, startOfWeek, addMonths, subMonths } from 'date-fns';
import './Calendar.css';
const Calendar = () => {
const [currentMonth, setCurrentMonth] = useState(new Date());
const header = () => {
return (
{format(currentMonth, 'MMMM yyyy')}
);
};
return (
{header()}
{/* Add more functionality here */}
);
};
export default Calendar;
In this component:
- We set up a state variable, currentMonth, to keep track of the current month.
- The header function displays the current month and provides buttons to navigate between months.
Implementing Date Navigation
With the basic setup done, we can enhance the functionality to display the dates of the current month. Add the following function to the Calendar component:
const getDaysInMonth = () => {
const startDate = startOfWeek(currentMonth);
const endDate = new Date(currentMonth.getFullYear(), currentMonth.getMonth() + 1, 0);
const days = [];
for (let date = startDate; date <= endDate; date.setDate(date.getDate() + 1)) {
days.push(new Date(date));
}
return days;
};
Next, we will render these days in the calendar:
return (
{header()}
{getDaysInMonth().map((day, index) => (
{format(day, 'd')}
))}
);
Each day will now be generated based on the current month!
Adding Event Management
To make our calendar more interactive, let’s add the ability to manage events. We’ll keep it simple by allowing users to click on a date to add an event.
First, modify your state to include events:
const [events, setEvents] = useState({});
Then, create a function to handle event creation:
const handleDayClick = (day) => {
const eventTitle = prompt('Enter event title:');
if (eventTitle) {
setEvents({
...events,
[format(day, 'yyyy-MM-dd')]: [...(events[format(day, 'yyyy-MM-dd')] || []), eventTitle]
});
}
};
This function prompts the user for an event title and updates the events state with the new event, keyed by the date.
Finally, modify your getDaysInMonth mapping to display events if exist:
{getDaysInMonth().map((day, index) => (
handleDayClick(day)}>
{format(day, 'd')}
{events[format(day, 'yyyy-MM-dd')] && events[format(day, 'yyyy-MM-dd')].map((event, idx) => (
{event}
))}
));}
Styling the Calendar
To give your calendar a nicer look, let’s add some CSS. Create a file named Calendar.css in the src directory and apply the following styles:
.calendar {
width: 300px;
border: 1px solid #ccc;
font-family: Arial, sans-serif;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
background: #f1f1f1;
padding: 10px;
}
.days {
display: grid;
grid-template-columns: repeat(7, 1fr);
}
.day {
padding: 10px;
border: 1px solid #eee;
text-align: center;
cursor: pointer;
}
.event {
background: #007BFF;
color: white;
margin: 2px;
padding: 2px 5px;
border-radius: 3px;
}
Conclusion
Congratulations! You have successfully built a simple calendar application using React from scratch. We explored how to set up a project, create components, handle state, and manage events. This project can serve as a solid foundation for more advanced functionalities, such as integrating with APIs, adding reminders, or improving the UI further.
As a developer, continuously enhancing your projects not only improves your coding skills but also adds to your portfolio. So, take this calendar application and extend it with more features. Happy coding!
