{"id":6488,"date":"2025-06-07T13:32:47","date_gmt":"2025-06-07T13:32:47","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=6488"},"modified":"2025-06-07T13:32:47","modified_gmt":"2025-06-07T13:32:47","slug":"build-a-calendar-in-react-from-scratch-5","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/build-a-calendar-in-react-from-scratch-5\/","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 component is a common requirement in web development. It can serve various purposes, such as scheduling, event management, or booking systems. In this tutorial, we will explore how to build a feature-rich calendar using React. This step-by-step guide will include managing state, handling user interactions, and applying some basic styling.<\/p>\n<h2>Prerequisites<\/h2>\n<p>Before diving in, ensure you have a solid understanding of:<\/p>\n<ul>\n<li>JavaScript ES6+<\/li>\n<li>React basics (components, state, and props)<\/li>\n<li>Basic CSS for styling<\/li>\n<\/ul>\n<h2>Setting Up the React Project<\/h2>\n<p>First, let&#8217;s set up a new React application using Create React App:<\/p>\n<pre>\n<code>npx create-react-app react-calendar<\/code>\n<\/pre>\n<p>After the setup, navigate to the project folder:<\/p>\n<pre>\n<code>cd react-calendar<\/code>\n<\/pre>\n<p>Now, start the development server:<\/p>\n<pre>\n<code>npm start<\/code>\n<\/pre>\n<h2>Creating the Calendar Component<\/h2>\n<p>Next, let&#8217;s create a new component for the calendar. Inside the <strong>src<\/strong> folder, create a new folder called <strong>components<\/strong> and add a file named <strong>Calendar.js<\/strong>.<\/p>\n<p>Here\u2019s the basic structure of the <strong>Calendar<\/strong> component:<\/p>\n<pre>\n<code>import React, { useState } from 'react';\nimport '.\/Calendar.css'; \/\/ Assuming you will style later\n\nconst Calendar = () =&gt; {\n    const [currentDate, setCurrentDate] = useState(new Date());\n\n    \/\/ Function to navigate to current month\n    const goToCurrentMonth = () =&gt; {\n        setCurrentDate(new Date());\n    };\n\n    return (\n        <div>\n            <header>\n                <h1>{currentDate.toLocaleString('default', { month: 'long' })} {currentDate.getFullYear()}<\/h1>\n                <button>Today<\/button>\n            <\/header>\n        <\/div>\n    );\n};\n\nexport default Calendar;<\/code>\n<\/pre>\n<h2>Understanding React State<\/h2>\n<p>In our Calendar component, we&#8217;ve used React&#8217;s <strong>useState<\/strong> hook to manage the current date. This allows us to update the calendar view dynamically as the user interacts with it.<\/p>\n<h2>Rendering Days of the Month<\/h2>\n<p>Next, we need to calculate the days in the current month and format them for display. Let\u2019s update our <strong>Calendar<\/strong> component:<\/p>\n<pre>\n<code>const Calendar = () =&gt; {\n    const [currentDate, setCurrentDate] = useState(new Date());\n\n    const getDaysInMonth = (date) =&gt; {\n        const year = date.getFullYear();\n        const month = date.getMonth();\n        return new Date(year, month + 1, 0).getDate();\n    };\n\n    const getFirstDayOfMonth = (date) =&gt; {\n        return new Date(date.getFullYear(), date.getMonth(), 1).getDay();\n    };\n\n    const renderDays = () =&gt; {\n        const daysInMonth = getDaysInMonth(currentDate);\n        const firstDay = getFirstDayOfMonth(currentDate);\n\n        let days = [];\n        for (let i = 1; i &lt;= daysInMonth; i++) {\n            days.push(<div>{i}<\/div>);\n        }\n\n        for (let i = 0; i &lt; firstDay; i++) {\n            days.unshift(<div><\/div>);\n        }\n        \n        return days;\n    };\n\n    return (\n        <div>\n            <header>\n                <h1>{currentDate.toLocaleString('default', { month: 'long' })} {currentDate.getFullYear()}<\/h1>\n                <button>Today<\/button>\n            <\/header>\n            <div>\n                {renderDays()}\n            <\/div>\n        <\/div>\n    );\n};<\/code>\n<\/pre>\n<h2>Adding Styles to Your Calendar<\/h2>\n<p>To make the calendar visually appealing, you will need to add some CSS styles. Create a <strong>Calendar.css<\/strong> file in the same folder:<\/p>\n<pre>\n<code>.calendar {\n    width: 300px;\n    margin: 20px auto;\n    border: 1px solid #ccc;\n}\nheader {\n    display: flex;\n    justify-content: space-between;\n    align-items: center;\n    background-color: #4CAF50;\n    color: white;\n    padding: 10px;\n}\n.days {\n    display: grid;\n    grid-template-columns: repeat(7, 1fr);\n    padding: 10px;\n}\n.day, .empty-day {\n    border: 1px solid #ddd;\n    height: 40px;\n    display: flex;\n    align-items: center;\n    justify-content: center;\n}\n.day:hover {\n    background-color: #f0f0f0;\n}\n.empty-day {\n    background-color: #f5f5f5;\n}<\/code>\n<\/pre>\n<h2>Handling Month Navigation<\/h2>\n<p>Now, let\u2019s add functionality to navigate between months. We will create two buttons, \u201cPrevious\u201d and \u201cNext.\u201d Update your <strong>Calendar<\/strong> component:<\/p>\n<pre>\n<code>const goToPreviousMonth = () =&gt; {\n    const newDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1);\n    setCurrentDate(newDate);\n};\n\nconst goToNextMonth = () =&gt; {\n    const newDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1);\n    setCurrentDate(newDate);\n};\n\nreturn (\n    <div>\n        <header>\n            <h1>{currentDate.toLocaleString('default', { month: 'long' })} {currentDate.getFullYear()}<\/h1>\n            <div>\n                <button>Previous<\/button>\n                <button>Next<\/button>\n                <button>Today<\/button>\n            <\/div>\n        <\/header>\n        <div>\n            {renderDays()}\n        <\/div>\n    <\/div>\n);<\/code>\n<\/pre>\n<h2>Complete Calendar Component Code<\/h2>\n<p>Here\u2019s the complete code for your calendar component:<\/p>\n<pre>\n<code>import React, { useState } from 'react';\nimport '.\/Calendar.css';\n\nconst Calendar = () =&gt; {\n    const [currentDate, setCurrentDate] = useState(new Date());\n\n    const getDaysInMonth = (date) =&gt; {\n        const year = date.getFullYear();\n        const month = date.getMonth();\n        return new Date(year, month + 1, 0).getDate();\n    };\n\n    const getFirstDayOfMonth = (date) =&gt; {\n        return new Date(date.getFullYear(), date.getMonth(), 1).getDay();\n    };\n\n    const renderDays = () =&gt; {\n        const daysInMonth = getDaysInMonth(currentDate);\n        const firstDay = getFirstDayOfMonth(currentDate);\n\n        let days = [];\n        for (let i = 1; i &lt;= daysInMonth; i++) {\n            days.push(<div>{i}<\/div>);\n        }\n\n        for (let i = 0; i &lt; firstDay; i++) {\n            days.unshift(<div><\/div>);\n        }\n\n        return days;\n    };\n\n    const goToPreviousMonth = () =&gt; {\n        const newDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1);\n        setCurrentDate(newDate);\n    };\n\n    const goToNextMonth = () =&gt; {\n        const newDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1);\n        setCurrentDate(newDate);\n    };\n\n    const goToCurrentMonth = () =&gt; {\n        setCurrentDate(new Date());\n    };\n\n    return (\n        <div>\n            <header>\n                <h1>{currentDate.toLocaleString('default', { month: 'long' })} {currentDate.getFullYear()}<\/h1>\n                <div>\n                    <button>Previous<\/button>\n                    <button>Next<\/button>\n                    <button>Today<\/button>\n                <\/div>\n            <\/header>\n            <div>\n                {renderDays()}\n            <\/div>\n        <\/div>\n    );\n};\n\nexport default Calendar;<\/code>\n<\/pre>\n<h2>Integrating the Calendar Component<\/h2>\n<p>Now that we have our Calendar component, let\u2019s integrate it into the main application. Open <strong>App.js<\/strong> and import the Calendar:<\/p>\n<pre>\n<code>import React from 'react';\nimport Calendar from '.\/components\/Calendar';\n\nfunction App() {\n    return (\n        <div>\n            \n        <\/div>\n    );\n}\n\nexport default App;<\/code>\n<\/pre>\n<h2>Testing Your Calendar<\/h2>\n<p>Finally, run your application and verify that the calendar displays correctly. You should be able to navigate between months and return to the current month.<\/p>\n<h2>Adding Additional Features<\/h2>\n<p>While we have created a basic calendar, you can extend its functionality by:<\/p>\n<ul>\n<li><strong>Add Events:<\/strong> Enable users to add events to specific dates.<\/li>\n<li><strong>Custom Styling:<\/strong> Enhance the design using CSS frameworks like Bootstrap or Material-UI.<\/li>\n<li><strong>Responsive Design:<\/strong> Make the calendar mobile-friendly with responsive layouts.<\/li>\n<li><strong>Keyboard Navigation:<\/strong> Allow users to navigate through the calendar using keyboard shortcuts.<\/li>\n<\/ul>\n<h2>Conclusion<\/h2>\n<p>In this tutorial, we built a functional calendar component from scratch using React. You learned to manage state, render dynamic content, and navigated through months effectively. This project serves as an excellent opportunity to solidify your React skills and explore further enhancements based on your application\u2019s requirements.<\/p>\n<p>Feel free to play around with the code and add more features to customize your calendar further!<\/p>\n<h2>Further Reading and Resources<\/h2>\n<ul>\n<li><a href=\"https:\/\/reactjs.org\/docs\/getting-started.html\" target=\"_blank\">React Documentation<\/a><\/li>\n<li><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Guide\" target=\"_blank\">JavaScript Guide &#8211; MDN<\/a><\/li>\n<li><a href=\"https:\/\/css-tricks.com\/\" target=\"_blank\">CSS-Tricks for styling tips<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Building a Calendar in React from Scratch Creating a calendar component is a common requirement in web development. It can serve various purposes, such as scheduling, event management, or booking systems. In this tutorial, we will explore how to build a feature-rich calendar using React. This step-by-step guide will include managing state, handling user interactions,<\/p>\n","protected":false},"author":82,"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-6488","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\/6488","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\/82"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=6488"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6488\/revisions"}],"predecessor-version":[{"id":6489,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/6488\/revisions\/6489"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=6488"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=6488"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=6488"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}