{"id":7457,"date":"2025-07-01T23:32:36","date_gmt":"2025-07-01T23:32:36","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=7457"},"modified":"2025-07-01T23:32:36","modified_gmt":"2025-07-01T23:32:36","slug":"build-a-calendar-in-react-from-scratch-9","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/build-a-calendar-in-react-from-scratch-9\/","title":{"rendered":"Build a Calendar in React from Scratch"},"content":{"rendered":"<h1>Build a Calendar in React from Scratch<\/h1>\n<p>Creating a calendar application can be a rewarding project for both new and seasoned developers. In this guide, we&#8217;ll walk through the process of building a calendar using React, exploring key concepts along the way while ensuring our application is functionally robust and visually appealing.<\/p>\n<h2>Table of Contents<\/h2>\n<ol>\n<li><a href=\"#setup\">Setting Up the Project<\/a><\/li>\n<li><a href=\"#basic-structure\">Basic Structure of the Calendar<\/a><\/li>\n<li><a href=\"#date-functions\">Date Functions<\/a><\/li>\n<li><a href=\"#calendar-component\">Creating the Calendar Component<\/a><\/li>\n<li><a href=\"#event-handling\">Event Handling<\/a><\/li>\n<li><a href=\"#styling\">Styling the Calendar<\/a><\/li>\n<li><a href=\"#final-thoughts\">Final Thoughts<\/a><\/li>\n<\/ol>\n<h2 id=\"setup\">Setting Up the Project<\/h2>\n<p>To get started, you&#8217;ll need to have Node.js and npm (Node Package Manager) installed. Once you&#8217;ve confirmed that you have those prerequisites, create a new React application using Create React App by running the following command in your terminal:<\/p>\n<pre><code>npx create-react-app react-calendar<\/code><\/pre>\n<p>Navigate into your project directory:<\/p>\n<pre><code>cd react-calendar<\/code><\/pre>\n<p>Now, open your project in your code editor of choice.<\/p>\n<h2 id=\"basic-structure\">Basic Structure of the Calendar<\/h2>\n<p>The calendar will consist of the following components:<\/p>\n<ul>\n<li><strong>Header:<\/strong> Displays the current month and year, along with navigation buttons to switch between months.<\/li>\n<li><strong>Days:<\/strong> Represents the grid of days for the current month.<\/li>\n<\/ul>\n<p>We&#8217;ll start by creating our main calendar component.<\/p>\n<h3>Creating the Calendar Component<\/h3>\n<p>Create a new file named <strong>Calendar.js<\/strong> in the <strong>src<\/strong> directory:<\/p>\n<pre><code>touch src\/Calendar.js<\/code><\/pre>\n<p>Now, let&#8217;s define our Calendar component:<\/p>\n<pre><code>\nimport React, { useState } from 'react';\n\nconst Calendar = () =&gt; {\n    const [currentDate, setCurrentDate] = useState(new Date());\n\n    return (\n        <div>\n            <h2>{currentDate.toLocaleString('default', { month: 'long' })} {currentDate.getFullYear()}<\/h2>\n            {\/* Additional components will go here *\/}\n        <\/div>\n    );\n};\n\nexport default Calendar;\n<\/code><\/pre>\n<p>In this initial setup, we have a simple Calendar component that utilizes React&#8217;s state to keep track of the current date.<\/p>\n<h2 id=\"date-functions\">Date Functions<\/h2>\n<p>To manage and display our calendar, we need utility functions to handle date calculations. Let&#8217;s create a new file named <strong>dateUtils.js<\/strong> in your <strong>src<\/strong> directory to house these utility functions:<\/p>\n<pre><code>\nexport const getDaysInMonth = (year, month) =&gt; new Date(year, month + 1, 0).getDate();\n\nexport const getFirstDayOfMonth = (year, month) =&gt; new Date(year, month, 1).getDay();\n\nexport const addMonths = (date, months) =&gt; {\n    const dateCopy = new Date(date);\n    dateCopy.setMonth(date.getMonth() + months);\n    return dateCopy;\n};\n<\/code><\/pre>\n<p>These functions will allow us to retrieve the number of days in a month, get the first day of the month (to adjust our calendar layout), and add or subtract months from our current date.<\/p>\n<h2 id=\"calendar-component\">Creating the Calendar Grid<\/h2>\n<p>Next, we will populate our Calendar component with grid cells representing the days of the month. Inside the <strong>Calendar.js<\/strong>, we will build the grid structure:<\/p>\n<pre><code>\nimport React, { useState } from 'react';\nimport { getDaysInMonth, getFirstDayOfMonth, addMonths } from '.\/dateUtils';\n\nconst Calendar = () =&gt; {\n    const [currentDate, setCurrentDate] = useState(new Date());\n\n    const daysInMonth = getDaysInMonth(currentDate.getFullYear(), currentDate.getMonth());\n    const firstDay = getFirstDayOfMonth(currentDate.getFullYear(), currentDate.getMonth());\n\n    const createCalendarGrid = () =&gt; {\n        const calendar = [];\n        for (let i = 0; i &lt; firstDay; i++) calendar.push(<td><\/td>); \/\/ Pre-fill the empty days\n        for (let day = 1; day &lt;= daysInMonth; day++) {\n            calendar.push(<td>{day}<\/td>);\n        }\n        return Array.from({ length: 6 }, (_, i) =&gt; (\n            <tr>{calendar.slice(i * 7, i * 7 + 7)}<\/tr>\n        ));\n    };\n\n    return (\n        <div>\n            <h2>{currentDate.toLocaleString('default', { month: 'long' })} {currentDate.getFullYear()}<\/h2>\n            <table>\n                <thead>\n                    <tr>\n                        <th>Sun<\/th>\n                        <th>Mon<\/th>\n                        <th>Tue<\/th>\n                        <th>Wed<\/th>\n                        <th>Thu<\/th>\n                        <th>Fri<\/th>\n                        <th>Sat<\/th>\n                    <\/tr>\n                <\/thead>\n                <tbody>\n                    {createCalendarGrid()}\n                <\/tbody>\n            <\/table>\n        <\/div>\n    );\n};\n\nexport default Calendar;\n<\/code><\/pre>\n<p>This code generates a calendar grid for the current month. It creates the appropriate number of empty cells based on the first day of the month and fills in the days of the month.<\/p>\n<h2 id=\"event-handling\">Event Handling<\/h2>\n<p>Next, we need to implement the functionality that allows users to navigate between months. We&#8217;ll add buttons to go to the previous and next months. Update the <strong>Calendar.js<\/strong> component as shown below:<\/p>\n<pre><code>\nimport React, { useState } from 'react';\nimport { getDaysInMonth, getFirstDayOfMonth, addMonths } from '.\/dateUtils';\n\nconst Calendar = () =&gt; {\n    const [currentDate, setCurrentDate] = useState(new Date());\n\n    const daysInMonth = getDaysInMonth(currentDate.getFullYear(), currentDate.getMonth());\n    const firstDay = getFirstDayOfMonth(currentDate.getFullYear(), currentDate.getMonth());\n\n    const createCalendarGrid = () =&gt; {\n        const calendar = [];\n        for (let i = 0; i &lt; firstDay; i++) calendar.push(<td><\/td>); \n        for (let day = 1; day &lt;= daysInMonth; day++) {\n            calendar.push(<td>{day}<\/td>);\n        }\n        return Array.from({ length: 6 }, (_, i) =&gt; (\n            <tr>{calendar.slice(i * 7, i * 7 + 7)}<\/tr>\n        ));\n    };\n\n    const handlePrevMonth = () =&gt; setCurrentDate(addMonths(currentDate, -1));\n    const handleNextMonth = () =&gt; setCurrentDate(addMonths(currentDate, 1));\n\n    return (\n        <div>\n            <h2>{currentDate.toLocaleString('default', { month: 'long' })} {currentDate.getFullYear()}<\/h2>\n            <button>Previous<\/button>\n            <button>Next<\/button>\n            <table>\n                <thead>\n                    <tr>\n                        <th>Sun<\/th>\n                        <th>Mon<\/th>\n                        <th>Tue<\/th>\n                        <th>Wed<\/th>\n                        <th>Thu<\/th>\n                        <th>Fri<\/th>\n                        <th>Sat<\/th>\n                    <\/tr>\n                <\/thead>\n                <tbody>\n                    {createCalendarGrid()}\n                <\/tbody>\n            <\/table>\n        <\/div>\n    );\n};\n\nexport default Calendar;\n<\/code><\/pre>\n<p>This implementation incorporates two buttons that allow users to navigate between months, updating the current date accordingly.<\/p>\n<h2 id=\"styling\">Styling the Calendar<\/h2>\n<p>No calendar is complete without a bit of styling. You can add the following CSS to your <strong>App.css<\/strong> file to improve the visual aesthetics of your calendar:<\/p>\n<pre><code>\ntable {\n    width: 100%;\n    border-collapse: collapse;\n}\n\nth, td {\n    border: 1px solid #ccc; \n    height: 50px; \n    text-align: center;\n}\n\nth {\n    background-color: #f4f4f4; \n}\n\nbutton {\n    margin: 10px;\n    padding: 10px 15px;\n    font-size: 16px;\n    cursor: pointer; \n}\n<\/code><\/pre>\n<p>This styling creates a clean and simple design for the calendar while ensuring that it remains user-friendly.<\/p>\n<h2 id=\"final-thoughts\">Final Thoughts<\/h2>\n<p>Congratulations! You have successfully built a calendar in React from scratch. This project allowed you to implement core React concepts such as state management, event handling, and functional programming. Feel free to expand upon this project by adding features like event creation, reminders, or even integrating it with a backend service for persistent event storage.<\/p>\n<p>As you continue your journey in React development, remember that building small projects is an excellent way to sharpen your skills and reinforce what you&#8217;ve learned. Happy coding!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Build a Calendar in React from Scratch Creating a calendar application can be a rewarding project for both new and seasoned developers. In this guide, we&#8217;ll walk through the process of building a calendar using React, exploring key concepts along the way while ensuring our application is functionally robust and visually appealing. Table of Contents<\/p>\n","protected":false},"author":85,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[398],"tags":[224],"class_list":["post-7457","post","type-post","status-publish","format-standard","category-react","tag-react"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7457","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/85"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=7457"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7457\/revisions"}],"predecessor-version":[{"id":7458,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7457\/revisions\/7458"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=7457"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=7457"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=7457"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}