Step-By-Step Guide To Creating a Calendar In React Native

 
 
Introduction 
 
React Native is one of the most effective JavaScript frameworks that can elevate your programming skills and development experience to a whole new level.
 
In this digital world, the professional and personal lifestyles of humans have changed since the last two decades. Our lives have not only become faster, but also hectic as we have to cope with so many things. So, applications that can plan schedules for people and let them know about day and month are essential. Having a calendar application can not only help you plan better schedules, but also make you aware of all the upcoming events and due dates during the month. Therefore, this post will explain building a calendar application using React Native programming language.
 
We are using React Native because it has everything a programmer could ask for to ensure a successful project execution and dynamic product development. Being a leading React Native programming development agency, we understand the requirement of the clients, so we tried to deliver an easy way to create a calendar component using the JavaScript framework.
 
Without wasting any more time, let's get into the step-by-step tutorial for creating a calendar in React Native.

Step 1: Get a Reliable IDE

With React Native programming language, it is required to install a couple of reliable files and software inside your system to create all the necessary dependencies to build your application. Therefore, we will use the simplest way to create a calendar component in React Native. We are going to use an all-in-one IDE that will require you no additional setup thanks to its plug-and-play feature.Use CodeSandbox to do the same. Just download and run the IDE.
 
Below is the directory structure that we are going to follow for this project:
 
 
Here’s the code for the calendar component.
 
Include the calendar component inside the index.js file.
  1. import React from "react";  
  2. import ReactDOM from "react-dom";  
  3.   
  4. import Calendar from "./components/calendar";  
  5.   
  6. function App() {  
  7. return (  
  8. <div className="App">  
  9. <Calendar />  
  10. </div>  
  11. );  
  12. }  
  13.   
  14. const rootElement = document.getElementById("root");  
  15. ReactDOM.render(<App />, rootElement);  
Please verify the output of the above code. You should see Calendar written as the heading in the output window. If you don't see that, make sure that you have written the correct code.
Now, we will create a layout that will display abbreviations of the days.

Step 2: Add Days

You need to install a moment and add a moment as the dependencies in React Native.
Now import the moment to the calendar component.
Import moment from 'moment.'
Now, use moment.weekdaysShort(); to get a short weekday.
  1. weekdayshort = moment.weekdaysShort();  
Synchronize the day feature with a function that returns a short day with <th>. The day will contain a short date name.
  1. let weekdayshortname = this.weekdayshort.map(day => {  
  2. return (  
  3. <th key={day} className="week-day">  
  4. {day}  
  5. </th>  
  6. );  
  7. });  
Now, you can get tail.Datetime, which is a beautiful CSS component that can improve the UI of the calendar component. 

Step 3: Locating the First Day of The Month

In any calendar, you will see that it starts on a particular day of each month.
Indeed, the first day of the month would be on different days for each month, but you have to decide which day would be the first day of the new week in your calendar. For that, create a moment state variable.
  1. state = {  
  2. dateObject: moment()  
  3. }  
The state of the variable would be modified through a third-party function that we are going to define below. Currently, we need to store the object of the moment, the first day of the month. We will be using a better method to store the first day of the month.
  1. firstDayOfMonth = () => {  
  2. let dateObject = this.state.dateObject;  
  3. let firstDay = moment(dateObject)  
  4. .startOf("month")  
  5. .format("d");  
  6. return firstDay;  
  7. };  
Now we will be creating a blank area to find the first date of the month.
  1. let blanks = [];  
  2. for (let i = 0; i < this.firstDayOfMonth(); i++) {  
  3. blanks.push(  
  4. <td className="calendar-day empty">{""}</td>  
  5. );  
  6. }  
Now, let’s generate </td> of date in the month.
  1. let daysInMonth = [];  
  2. for (let d = 1; d <= this.daysInMonth(); d++) {  
  3. daysInMonth.push(  
  4. <td key={d} className="calendar-day">  
  5. {d}  
  6. </td>  
  7. );  
  8. }  
Let's define some more variables for better execution.
totalSlots contains blanks and daysInMonth using the operator. These variables have dynamic values.
rows hold </td>while going to a new row
cells contain each </td> to assign to each row
  1. var totalSlots = [...blanks, ...daysInMonth];  
  2. let rows = [];  
  3. let cells = [];  
Now, we will go through totalSlots to get a calendar structure week.
  1. totalSlots.forEach((row, i) => {  
  2. if (i % 7 !== 0) {  
  3. cells.push(row); // if index not equal 7 that means not go to next week  
  4. else {  
  5. rows.push(cells); // when reach next week we contain all td in last week to rows  
  6. cells = []; // empty container  
  7. cells.push(row); // in current loop we still push current row to new container  
  8. }  
  9. if (i === totalSlots.length - 1) { // when end loop we add remain date  
  10. rows.push(cells);  
  11. }  
  12. });  
Wrap all rows in </td>
  1. let daysinmonth = rows.map((d, i) => {  
  2. return <tr>{d}</tr>;  
  3. });  
And the </td> in <tbody>
  1. <table className="calendar-day">  
  2. <thead>  
  3. <tr>{weekdayshortname}</tr>  
  4. </thead>  
  5. <tbody>{daysinmonth}</tbody>  
  6. </table>  
Now, you should see the correct day along with the right date, so everything falls in place.

Step 4: Highlight the Current Day

  1. currentDay = () => {  
  2. return this.state.dateObject.format("D");  
  3. };  
The above code will find the current date.
  1. let daysInMonth = [];  
  2. for (let d = 1; d <= this.daysInMonth(); d++){  
  3. let currentDay = d == this.currentDay() ? "today" : "";  
  4. daysInMonth.push(  
  5. <td key={d} className={`calendar-day ${currentDay}`}>  
  6. {d}  
  7. </td>);  
  8. }  
  9. }  
To verify if the current date is correct or not, we are going to put a conditional operator. If the returned value is correct, we will add a class today while pushing to the daysInMonth.
  1. let daysInMonth = [];  
  2. for (let d = 1; d <= this.daysInMonth(); d++){  
  3. let currentDay = d == this.currentDay() ? "today" : "";  
  4. daysInMonth.push(  
  5. <td key={d} className={`calendar-day ${currentDay}`}>  
  6. {d}  
  7. </td>);  
  8. }  
  9. }  
Now, we will add a function to pick a month of our choice.

Step 5: Add Name of Months

After the calendar table div, insert the month picker div.
  1. return (  
  2. <div className="tail-datetime-calendar">  
  3. <div className="calendar-navi">  
  4. </div>  
  5. )  
Insert the current month name with momentObject.
  1. month = () => {  
  2. return this.state.dateObject.format("MMMM");  
  3. };  
Show the month in div.
  1. return (  
  2.         <div className="tail-datetime-calendar">  
  3.         <div className="calendar-navi">  
  4.            {this.month()}  
  5.         </div>  
  6. )  
  7.   
  8. <span data-tail-navi="switch" class="calendar-label">  
  9.        {this.month()}  
  10. </span>  
Now, you should be able to see the name of the month above the calendar table with an attractive layout.
We need to write the code that changes the name of the month as time goes. Otherwise, the current name of the month will be displayed throughout the year. We will write a render function that will render the month table. With the help of moment object, get all months and assign them to allMonths state.

For learning in detail about this, you must have knowledge about the Core Concept Of React. It will help you all in the long run.
  1. state = {  
  2. dateObject: moment(),  
  3. allmonths :moment.months()  
  4. };  
Now, develop another function to handle this month's table.
  1. MonthList = props => {}  
Props are the selected month object (Jan-Dec).
  1. let months = [];  
  2. props.data.map(data => {  
  3. months.push(  
  4. <td>  
  5. <span>{data}</span>  
  6. </td>  
  7. );  
  8. });  
Now we will need to define the cells that contain the name of the month.
  1. let rows = [];  
  2. let cells = [];  
Grab the condition from the calendar table for this table
  1. months.forEach((row, i) => {  
  2. if (i % 3 !== 0 || i == 0) { // except zero index  
  3. cells.push(row);  
  4. else {  
  5. rows.push(cells);  
  6. cells = [];  
  7. cells.push(row);  
  8. }  
  9. });  
  10. rows.push(cells); // add last row  
Map over the rows and wrap them in <tr>
  1. let monthlist = rows.map((d, i) => {  
  2. return <tr>{d}</tr>;  
  3. });  
Now, return the proper table in HTML, styled with some tail.Datetime CSS.
  1. return (  
  2. <table className="calendar-month">  
  3. <thead>  
  4. <tr>  
  5. <th colSpan="4">Select a Month</th>  
  6. </tr>  
  7. </thead>  
  8. <tbody>{monthlist}</tbody>  
  9. </table>  
  10. );
Now, we need to render the program in the parent.
  1. <div className="calendar-date">  
  2. <this.MonthList data={moment.months()} />  
  3. </div>  
In the output, you will also get another table that will display the name of the month. Observe that these names are not clickable, and based on the month you click, the below part of the calendar is not changing accordingly. To do that, we will write the code below.

Step 6: Sync Months with Dates

Create a setMonth function.
  1. setMonth = month => {  
  2. let monthNo = this.months.indexOf(month);// get month number  
  3. let dateObject = Object.assign({}, this.state.dateObject);  
  4. dateObject = moment(dateObject).set("month", monthNo); // change month value  
  5. this.setState({  
  6. dateObject: dateObject // add to state  
  7. });  
  8. };  
Add it to <td>
  1. props.data.map(data => {  
  2. months.push(  
  3. <td  
  4. key={data}  
  5. className="calendar-month"  
  6. onClick={e => {  
  7. this.setMonth(data);  
  8. }}  
  9. >  
  10. <span>{data}</span>  
  11. </td>  
  12. );  
  13. });  
Now, whenever you click on the name of the month, the calendar should change accordingly, along with the right dates. The table of month picker is currently creating redundancy and not required to be there all the time. You can also hide that month picker table as soon as it is selected. Add a showMonthTable state to do this task.
  1. state = {  
  2. showMonthTable:false,  
  3. dateObject: moment(),  
  4. allmonths: moment.months()  
  5. };  
To hide on first T load, add a simple check state in the calendar-date div.
  1. <div className="calendar-date">  
  2. {this.state.showMonthTable &&  
  3. this.MonthList data = {moment.months()} />}  
  4. </div>  
With this dress code, the month table will be hidden, and the selected name of the month will be displayed at the top of the date table. We need to create a showTable method that will display the table of the month name when the user clicks it.
  1. <div className="calendar-navi"  
  2. onClick={e => {  
  3. this.showMonth();  
  4. }}  
  5. >  
Define the action to toggle the state.
  1. showMonth = (e, month) => {  
  2. this.setState({  
  3. showMonthTable: !this.state.showMonthTable  
  4. });  
  5. };  
When you click on the selector, the calendar layout expands, and the names of the months are also being displayed.
However, a great unique experience should display only one table at a time.
To do that, you can write the code below.
  1. { !this.state.showMonthTable && (  
  2. <div className="calendar-date">  
  3. <table className="calendar-day">  
  4. <thead>  
  5. <tr>{weekdayshortname}</tr>  
  6. </thead>  
  7. <tbody>{daysinmonth}</tbody>  
  8. </table>  
  9. </div>)}  
This code will only make one table active at a time. Whenever you choose to change the name of the month, the table of the date will be hidden and vice versa.

Conclusion

Please let me know your thoughts about this article and how you are planning to build your calendar component in React Native.
I would love to know your feedback in the comments below.

Next Recommended Reading How To Create A Simple React App