{"id":5698,"date":"2025-05-12T19:32:30","date_gmt":"2025-05-12T19:32:30","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=5698"},"modified":"2025-05-12T19:32:30","modified_gmt":"2025-05-12T19:32:30","slug":"build-a-calendar-in-react-from-scratch-2","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/build-a-calendar-in-react-from-scratch-2\/","title":{"rendered":"Build a Calendar in React from Scratch"},"content":{"rendered":"<h1>Building a Calendar in React from Scratch<\/h1>\n<p>If you&#8217;ve ever needed to incorporate a calendar into your web application, building one from scratch using React can be a rewarding challenge. In this tutorial, we&#8217;ll guide you through every step, from setting up your environment to implementing features like month navigation and event display. By the end, you\u2019ll have a fully functional calendar component that can be a robust base for further enhancements.<\/p>\n<h2>Table of Contents<\/h2>\n<ul>\n<li><a href=\"#setup\">Setting Up Your Environment<\/a><\/li>\n<li><a href=\"#core\">Core Calendar Structure<\/a><\/li>\n<li><a href=\"#navigation\">Implementing Month Navigation<\/a><\/li>\n<li><a href=\"#events\">Adding Events<\/a><\/li>\n<li><a href=\"#styling\">Styling Your Calendar<\/a><\/li>\n<li><a href=\"#wrapup\">Wrapping Up<\/a><\/li>\n<\/ul>\n<h2 id=\"setup\">1. Setting Up Your Environment<\/h2>\n<p>To begin, you\u2019ll need to set up your React development environment. If you have Node.js installed, creating a new React app is simple. Open your terminal and run:<\/p>\n<pre>\n<code>\nnpx create-react-app calendar-app\ncd calendar-app\nnpm start\n<\/code>\n<\/pre>\n<p>This command will create a new React application called <strong>calendar-app<\/strong> and open it in your default browser.<\/p>\n<h2 id=\"core\">2. Core Calendar Structure<\/h2>\n<p>Now that our development environment is ready, let&#8217;s create a basic calendar structure. Replace the contents of <code>src\/App.js<\/code> with the following code:<\/p>\n<pre>\n<code>\nimport React, { useState } from 'react';\n\nconst App = () =&gt; {\n    const [currentDate, setCurrentDate] = useState(new Date());\n    \n    const getDaysInMonth = (date) =&gt; {\n        let year = date.getFullYear();\n        let month = date.getMonth();\n        return new Date(year, month + 1, 0).getDate();\n    };\n\n    const generateCalendar = () =&gt; {\n        const daysInMonth = getDaysInMonth(currentDate);\n        let daysArray = [];\n        for (let day = 1; day &lt;= daysInMonth; day++) {\n            daysArray.push(day);\n        }\n        return daysArray;\n    };\n\n    return (\n        <div>\n            <h1>{currentDate.toLocaleString('default', { month: 'long' })} {currentDate.getFullYear()}<\/h1>\n            <div>\n                {generateCalendar().map(day =&gt; (\n                    <div>{day}<\/div>\n                ))}\n            <\/div>\n        <\/div>\n    );\n};\n\nexport default App;\n<\/code>\n<\/pre>\n<p>In this code, we&#8217;re using React&#8217;s <strong>useState<\/strong> hook to manage the current date and a function to generate the days of the month. We then render these days in a grid layout.<\/p>\n<h2 id=\"navigation\">3. Implementing Month Navigation<\/h2>\n<p>Next, let&#8217;s add navigation functionality to switch between months. Update the <code>App.js<\/code> file to include buttons for navigating through the months:<\/p>\n<pre>\n<code>\nconst App = () =&gt; {\n    \/\/ ... existing code\n\n    const goToPreviousMonth = () =&gt; {\n        const newDate = new Date(currentDate.setMonth(currentDate.getMonth() - 1));\n        setCurrentDate(newDate);\n    };\n\n    const goToNextMonth = () =&gt; {\n        const newDate = new Date(currentDate.setMonth(currentDate.getMonth() + 1));\n        setCurrentDate(newDate);\n    };\n\n    return (\n        <div>\n            <button>Previous<\/button>\n            <button>Next<\/button>\n            <h1>{currentDate.toLocaleString('default', { month: 'long' })} {currentDate.getFullYear()}<\/h1>\n            <div>\n                {generateCalendar().map(day =&gt; (\n                    <div>{day}<\/div>\n                ))}\n            <\/div>\n        <\/div>\n    );\n};\n<\/code>\n<\/pre>\n<p>Now, users can navigate to previous and next months. The <strong>goToPreviousMonth<\/strong> and <strong>goToNextMonth<\/strong> functions adjust the current date accordingly.<\/p>\n<h2 id=\"events\">4. Adding Events<\/h2>\n<p>To make our calendar functional, let&#8217;s implement an event feature. We&#8217;ll create a simple form to add events to specific days. Let\u2019s modify the code to store events:<\/p>\n<pre>\n<code>\nconst App = () =&gt; {\n    const [events, setEvents] = useState({});\n    const [eventInput, setEventInput] = useState('');\n\n    const addEvent = (day) =&gt; {\n        const key = `${currentDate.getFullYear()}-${currentDate.getMonth() + 1}-${day}`;\n        setEvents({\n            ...events,\n            [key]: [...(events[key] || []), eventInput]\n        });\n        setEventInput('');\n    };\n\n    return (\n        <div>\n            <button>Previous<\/button>\n            <button>Next<\/button>\n            <h1>{currentDate.toLocaleString('default', { month: 'long' })} {currentDate.getFullYear()}<\/h1>\n            <div>\n                {generateCalendar().map(day =&gt; (\n                    <div>\n                        <p>{day}<\/p>\n                        <ul>\n                            {(events[`${currentDate.getFullYear()}-${currentDate.getMonth() + 1}-${day}`] || []).map((event, index) =&gt; (\n                                <li>{event}<\/li>\n                            ))}\n                        <\/ul>\n                         setEventInput(e.target.value)} \n                            placeholder=\"Add event\" \n                        \/&gt;\n                        <button> addEvent(day)}&gt;Add<\/button>\n                    <\/div>\n                ))}\n            <\/div>\n        <\/div>\n    );\n};\n<\/code>\n<\/pre>\n<p>In this modification, we introduce:<\/p>\n<ul>\n<li><strong>events<\/strong>: A state variable that keeps track of events for each day.<\/li>\n<li><strong>eventInput<\/strong>: A state variable for the input field where users can type their event.<\/li>\n<li><strong>addEvent<\/strong>: A function that takes the day, stores the event against the specific day\u2019s key within the events object.<\/li>\n<\/ul>\n<h2 id=\"styling\">5. Styling Your Calendar<\/h2>\n<p>Styling is crucial to making your calendar visually appealing. Let\u2019s add some basic CSS. Create a file called <code>src\/App.css<\/code> and add the following styles:<\/p>\n<pre>\n<code>\n.calendar {\n    display: grid;\n    grid-template-columns: repeat(7, 1fr);\n    gap: 5px;\n}\n\n.day {\n    border: 1px solid #ccc;\n    padding: 10px;\n    height: 100px;\n}\n\ninput {\n    margin-top: 5px;\n    width: 80%;\n}\n\nbutton {\n    margin-top: 5px;\n}\n<\/code>\n<\/pre>\n<p>Import the CSS into your <code>App.js<\/code>:<\/p>\n<pre>\n<code>\nimport '.\/App.css';\n<\/code>\n<\/pre>\n<p>This CSS will give you a basic layout with a grid structure for the calendar and styling for the event input fields.<\/p>\n<h2 id=\"wrapup\">6. Wrapping Up<\/h2>\n<p>Congratulations! You&#8217;ve successfully built a calendar in React from scratch. You now have a foundational calendar app with month navigation and event management features. The next steps in enhancement may include:<\/p>\n<ul>\n<li>Adding more complex event functionalities (like editing and deleting events).<\/li>\n<li>Adding support for multiple users\/events.<\/li>\n<li>Integrating with APIs for better data handling.<\/li>\n<\/ul>\n<p>By utilizing React&#8217;s component-driven architecture, you can further expand your calendar to meet any requirements you may have.<\/p>\n<p>Happy coding!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Building a Calendar in React from Scratch If you&#8217;ve ever needed to incorporate a calendar into your web application, building one from scratch using React can be a rewarding challenge. In this tutorial, we&#8217;ll guide you through every step, from setting up your environment to implementing features like month navigation and event display. By the<\/p>\n","protected":false},"author":102,"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-5698","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\/5698","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\/102"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=5698"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/5698\/revisions"}],"predecessor-version":[{"id":5699,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/5698\/revisions\/5699"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=5698"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=5698"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=5698"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}