{"id":7250,"date":"2025-06-25T11:32:39","date_gmt":"2025-06-25T11:32:39","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=7250"},"modified":"2025-06-25T11:32:39","modified_gmt":"2025-06-25T11:32:39","slug":"build-a-calendar-in-react-from-scratch-6","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/build-a-calendar-in-react-from-scratch-6\/","title":{"rendered":"Build a Calendar in React from Scratch"},"content":{"rendered":"<h1>Building a Calendar in React from Scratch<\/h1>\n<p>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\u2019ll walk through the process of building a simple, functional calendar from scratch using React.<\/p>\n<h2>Table of Contents<\/h2>\n<ul>\n<li><a href=\"#setup\">Project Setup<\/a><\/li>\n<li><a href=\"#calendar-component\">Creating the Calendar Component<\/a><\/li>\n<li><a href=\"#date-navigation\">Implementing Date Navigation<\/a><\/li>\n<li><a href=\"#event-management\">Adding Event Management<\/a><\/li>\n<li><a href=\"#styling\">Styling the Calendar<\/a><\/li>\n<li><a href=\"#conclusion\">Conclusion<\/a><\/li>\n<\/ul>\n<h2 id=\"setup\">Project Setup<\/h2>\n<p>First, you&#8217;ll need to set up a new React project. If you haven&#8217;t already, you can create a new React app using Create React App by running the following command:<\/p>\n<pre><code>npx create-react-app react-calendar<\/code><\/pre>\n<p>Once your project is created, navigate into your project directory:<\/p>\n<pre><code>cd react-calendar<\/code><\/pre>\n<p>Next, install the necessary dependencies for date manipulation. We\u2019ll use <strong>date-fns<\/strong>:<\/p>\n<pre><code>npm install date-fns<\/code><\/pre>\n<h2 id=\"calendar-component\">Creating the Calendar Component<\/h2>\n<p>Now that we have our environment set up, let\u2019s create a simple Calendar component. Create a new file named <strong>Calendar.js<\/strong> in the <strong>src<\/strong> directory and open it. Here\u2019s a basic structure to get started:<\/p>\n<pre><code>import React, { useState } from 'react';\nimport { format, startOfWeek, addMonths, subMonths } from 'date-fns';\nimport '.\/Calendar.css';\n\nconst Calendar = () =&gt; {\n    const [currentMonth, setCurrentMonth] = useState(new Date());\n\n    const header = () =&gt; {\n        return (\n            <div>\n                <h2>{format(currentMonth, 'MMMM yyyy')}<\/h2>\n                <button> setCurrentMonth(subMonths(currentMonth, 1))}&gt;&lt;<\/button>\n                <button> setCurrentMonth(addMonths(currentMonth, 1))}&gt;&gt;<\/button>\n            <\/div>\n        );\n    };\n\n    return (\n        <div>\n            {header()}\n            {\/* Add more functionality here *\/}\n        <\/div>\n    );\n};\n\nexport default Calendar;<\/code><\/pre>\n<p>In this component:<\/p>\n<ul>\n<li>We set up a state variable, <strong>currentMonth<\/strong>, to keep track of the current month.<\/li>\n<li>The <strong>header<\/strong> function displays the current month and provides buttons to navigate between months.<\/li>\n<\/ul>\n<h2 id=\"date-navigation\">Implementing Date Navigation<\/h2>\n<p>With the basic setup done, we can enhance the functionality to display the dates of the current month. Add the following function to the <strong>Calendar<\/strong> component:<\/p>\n<pre><code>const getDaysInMonth = () =&gt; {\n    const startDate = startOfWeek(currentMonth);\n    const endDate = new Date(currentMonth.getFullYear(), currentMonth.getMonth() + 1, 0);\n    const days = [];\n    \n    for (let date = startDate; date &lt;= endDate; date.setDate(date.getDate() + 1)) {\n        days.push(new Date(date));\n    }\n    return days;\n};<\/code><\/pre>\n<p>Next, we will render these days in the calendar:<\/p>\n<pre><code>return (\n    <div>\n        {header()}\n        <div>\n            {getDaysInMonth().map((day, index) =&gt; (\n                <div>\n                    {format(day, 'd')}\n                <\/div>\n            ))}\n        <\/div>\n    <\/div>\n);<\/code><\/pre>\n<p>Each day will now be generated based on the current month!<\/p>\n<h2 id=\"event-management\">Adding Event Management<\/h2>\n<p>To make our calendar more interactive, let&#8217;s add the ability to manage events. We\u2019ll keep it simple by allowing users to click on a date to add an event.<\/p>\n<p>First, modify your state to include events:<\/p>\n<pre><code>const [events, setEvents] = useState({});<\/code><\/pre>\n<p>Then, create a function to handle event creation:<\/p>\n<pre><code>const handleDayClick = (day) =&gt; {\n        const eventTitle = prompt('Enter event title:');\n        if (eventTitle) {\n            setEvents({\n                ...events,\n                [format(day, 'yyyy-MM-dd')]: [...(events[format(day, 'yyyy-MM-dd')] || []), eventTitle]\n            });\n        }\n};<\/code><\/pre>\n<p>This function prompts the user for an event title and updates the <strong>events<\/strong> state with the new event, keyed by the date.<\/p>\n<p>Finally, modify your <strong>getDaysInMonth<\/strong> mapping to display events if exist:<\/p>\n<pre><code>{getDaysInMonth().map((day, index) =&gt; (\n    <div> handleDayClick(day)}&gt;\n        {format(day, 'd')}\n        {events[format(day, 'yyyy-MM-dd')] &amp;&amp; events[format(day, 'yyyy-MM-dd')].map((event, idx) =&gt; (\n            <div>{event}<\/div>\n        ))}\n    <\/div>\n));}<\/code><\/pre>\n<h2 id=\"styling\">Styling the Calendar<\/h2>\n<p>To give your calendar a nicer look, let\u2019s add some CSS. Create a file named <strong>Calendar.css<\/strong> in the <strong>src<\/strong> directory and apply the following styles:<\/p>\n<pre><code>.calendar {\n    width: 300px;\n    border: 1px solid #ccc;\n    font-family: Arial, sans-serif;\n}\n\n.header {\n    display: flex;\n    justify-content: space-between;\n    align-items: center;\n    background: #f1f1f1;\n    padding: 10px;\n}\n\n.days {\n    display: grid;\n    grid-template-columns: repeat(7, 1fr);\n}\n\n.day {\n    padding: 10px;\n    border: 1px solid #eee;\n    text-align: center;\n    cursor: pointer;\n}\n\n.event {\n    background: #007BFF;\n    color: white;\n    margin: 2px;\n    padding: 2px 5px;\n    border-radius: 3px;\n}<\/code><\/pre>\n<h2 id=\"conclusion\">Conclusion<\/h2>\n<p>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.<\/p>\n<p>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!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>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\u2019ll walk through the process of<\/p>\n","protected":false},"author":88,"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-7250","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\/7250","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\/88"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=7250"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7250\/revisions"}],"predecessor-version":[{"id":7251,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7250\/revisions\/7251"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=7250"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=7250"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=7250"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}