{"id":6412,"date":"2025-06-05T05:32:44","date_gmt":"2025-06-05T05:32:44","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=6412"},"modified":"2025-06-05T05:32:44","modified_gmt":"2025-06-05T05:32:44","slug":"build-a-calendar-in-react-from-scratch-4","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/build-a-calendar-in-react-from-scratch-4\/","title":{"rendered":"Build a Calendar in React from Scratch"},"content":{"rendered":"<h1>Build a Calendar in React from Scratch<\/h1>\n<p>In today\u2019s article, we\u2019ll 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.<\/p>\n<h2>Table of Contents<\/h2>\n<ul>\n<li><a href=\"#getting-started\">Getting Started<\/a><\/li>\n<li><a href=\"#setting-up-environment\">Setting Up the Environment<\/a><\/li>\n<li><a href=\"#project-structure\">Project Structure<\/a><\/li>\n<li><a href=\"#creating-calendar\">Creating the Calendar Component<\/a><\/li>\n<li><a href=\"#handling-navigation\">Handling Navigation<\/a><\/li>\n<li><a href=\"#date-selection\">Implementing Date Selection<\/a><\/li>\n<li><a href=\"#styling-calendar\">Styling the Calendar<\/a><\/li>\n<li><a href=\"#conclusion\">Conclusion<\/a><\/li>\n<\/ul>\n<h2 id=\"getting-started\">Getting Started<\/h2>\n<p>Before we dive into coding, it&#8217;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&#8217;ll cover all the essential steps needed to create a calendar from scratch.<\/p>\n<h2 id=\"setting-up-environment\">Setting Up the Environment<\/h2>\n<p>To start building our calendar, we need a React environment. You can quickly set it up using Create React App. If you haven\u2019t installed Create React App yet, you can do it using the following command:<\/p>\n<pre><code>npx create-react-app my-calendar<\/code><\/pre>\n<p>Navigate into your new project folder:<\/p>\n<pre><code>cd my-calendar<\/code><\/pre>\n<p>Once you&#8217;re in the project directory, you can start your development server:<\/p>\n<pre><code>npm start<\/code><\/pre>\n<p>Your default browser should now open up with your new React app running.<\/p>\n<h2 id=\"project-structure\">Project Structure<\/h2>\n<p>For our calendar application, we\u2019ll set up a simple project structure. You can create a folder named <strong>components<\/strong> in the <strong>src<\/strong> folder, where we will store our calendar component. The structure should look like this:<\/p>\n<pre><code>\nmy-calendar\/\n\u251c\u2500\u2500 src\/\n\u2502   \u251c\u2500\u2500 components\/\n\u2502   \u2502   \u2514\u2500\u2500 Calendar.js\n\u2502   \u2514\u2500\u2500 App.js\n...<\/code><\/pre>\n<h2 id=\"creating-calendar\">Creating the Calendar Component<\/h2>\n<p>Let&#8217;s create the Calendar component. Open <strong>Calendar.js<\/strong> and add the following code:<\/p>\n<pre><code>import React, { useState } from 'react';\n\nconst Calendar = () =&gt; {\n    const [currentDate, setCurrentDate] = useState(new Date());\n\n    const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];\n    const monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];\n\n    const getDaysInMonth = (month, year) =&gt; {\n        return new Date(year, month + 1, 0).getDate();\n    };\n\n    const getFirstDayOfMonth = (month, year) =&gt; {\n        return new Date(year, month, 1).getDay();\n    };\n\n    const renderCalendar = () =&gt; {\n        const daysInMonth = getDaysInMonth(currentDate.getMonth(), currentDate.getFullYear());\n        const firstDay = getFirstDayOfMonth(currentDate.getMonth(), currentDate.getFullYear());\n        const days = [];\n\n        for(let i = 0; i &lt; firstDay; i++) {\n            days.push(<div \/>);\n        }\n        for(let day = 1; day &lt;= daysInMonth; day++) {\n            days.push(<div>{day}<\/div>);\n        }\n\n        return days;\n    };\n\n    return (\n        <div>\n            <div>\n                <h2>{monthNames[currentDate.getMonth()]} {currentDate.getFullYear()}<\/h2>\n            <\/div>\n            <div>\n                {dayNames.map(day =&gt; <div>{day}<\/div>)}\n                {renderCalendar()}\n            <\/div>\n        <\/div>\n    );\n};\n\nexport default Calendar;<\/code><\/pre>\n<p>In this component:<\/p>\n<ul>\n<li>We\u2019re using React&#8217;s <strong>useState<\/strong> hook to manage the current date.<\/li>\n<li>We defined two helper functions to get the number of days in a month and the starting day of the month.<\/li>\n<li>The <strong>renderCalendar<\/strong> function generates the calendar days dynamically.<\/li>\n<\/ul>\n<h2 id=\"handling-navigation\">Handling Navigation<\/h2>\n<p>Now that we have our calendar display set up, let\u2019s add navigation to switch between months. We&#8217;ll add buttons to navigate to the previous and next months:<\/p>\n<pre><code>const handlePreviousMonth = () =&gt; {\n    setCurrentDate(new Date(currentDate.getFullYear(), currentDate.getMonth() - 1));\n};\n\nconst handleNextMonth = () =&gt; {\n    setCurrentDate(new Date(currentDate.getFullYear(), currentDate.getMonth() + 1));\n};\n<\/code><\/pre>\n<p>We\u2019ll now update the return statement in our <strong>Calendar<\/strong> component to include these buttons:<\/p>\n<pre><code>return (\n    <div>\n        <div>\n            <button>Previous<\/button>\n            <h2>{monthNames[currentDate.getMonth()]} {currentDate.getFullYear()}<\/h2>\n            <button>Next<\/button>\n        <\/div>\n        <div>\n            {dayNames.map(day =&gt; <div>{day}<\/div>)}\n            {renderCalendar()}\n        <\/div>\n    <\/div>\n);<\/code><\/pre>\n<h2 id=\"date-selection\">Implementing Date Selection<\/h2>\n<p>Next, we want to allow users to select a date. To achieve this, we will modify the <strong>renderCalendar<\/strong> function to handle clicks on the days:<\/p>\n<pre><code>const handleDayClick = (day) =&gt; {\n    alert(`Selected date: ${day} ${monthNames[currentDate.getMonth()]} ${currentDate.getFullYear()}`);\n};\n\n...\n\ndays.push(\n    <div> handleDayClick(day)}\n    &gt;\n        {day}\n    <\/div>\n);<\/code><\/pre>\n<p>Now, clicking a day will cause an alert to show the selected date.<\/p>\n<h2 id=\"styling-calendar\">Styling the Calendar<\/h2>\n<p>To make our calendar look visually appealing, let&#8217;s add some basic CSS. Create a new file named <strong>Calendar.css<\/strong> in the same <strong>components<\/strong> folder and import it into your <strong>Calendar.js<\/strong> component:<\/p>\n<pre><code>import '.\/Calendar.css';<\/code><\/pre>\n<p>Now, add the following CSS styles to <strong>Calendar.css<\/strong>:<\/p>\n<pre><code>.calendar {\n    display: flex;\n    flex-direction: column;\n    align-items: center;\n    margin: 20px;\n}\n\n.header {\n    display: flex;\n    justify-content: space-between;\n    width: 100%;\n}\n\n.days {\n    display: grid;\n    grid-template-columns: repeat(7, 1fr);\n    gap: 5px;\n    margin-top: 10px;\n}\n\n.day, .day-name {\n    width: 40px;\n    height: 40px;\n    display: flex;\n    justify-content: center;\n    align-items: center;\n    border: 1px solid #ccc;\n    border-radius: 5px;\n}\n\n.day:hover {\n    background-color: #f0f0f0;\n    cursor: pointer;\n}\n<\/code><\/pre>\n<h2 id=\"conclusion\">Conclusion<\/h2>\n<p>Congratulations! You\u2019ve now created a simple yet functional calendar component in React. You have learned how to:<\/p>\n<ul>\n<li>Set up a React environment using Create React App.<\/li>\n<li>Create a calendar component and manage its state.<\/li>\n<li>Implement month navigation and date selection.<\/li>\n<li>Style the calendar for a better user experience.<\/li>\n<\/ul>\n<p>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!<\/p>\n<p>Feel free to explore and expand on this basic implementation. Happy coding!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Build a Calendar in React from Scratch In today\u2019s article, we\u2019ll 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,<\/p>\n","protected":false},"author":78,"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":{"0":"post-6412","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-react","7":"tag-react"},"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6412","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\/78"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=6412"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6412\/revisions"}],"predecessor-version":[{"id":6413,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6412\/revisions\/6413"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=6412"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=6412"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=6412"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}