Project 1: Custom React calendar with hooks

Vibin VS
3 min readMar 21, 2021

I am trying to do a challenge similar to 100daysOfCode, but this is a little different, I have named it 100 projects in a year, Since I am working full-time and have loads of work already with constant app updates, I decided this process would be less hectic and also will keep me motivated to learn new stuff. First I am going to start with simple projects. I always dive hard into stuff and leave it off halfway, so I am gonna start with simple ones and move towards hard ones gradually.

I have started with a simple calendar, mostly without using any external libraries, I have used Moment.js for dates.

Calendar with minimum design

Let's dive into the code now

First lets us create a new project using:

npx create-react-app hooks-calendar

once the project is created install Moment.js using :

npm install moment — save

remove the boilerplate code in App.js and create a file named Calendar.js

The file structure will look something like this

import the Calender.js to the app and create two states one for the current moment and another for the selected moment.

App.js with the calendar component

Now, let’s move to the calendar creation :P

states initilisation and days header

Since I have planned to add few more features to the calendar in future updates, I have used useReducer hooks instead of useState.

Return statement

This will be the code to return statement, I have used inline-styling on all the elements for the purpose of the article, but it is always preferable and also good coding practice to use a CSS file or any other pre-processors like SASS.

Now, let us move to the real deal of the calendar.

days() function in return
function which contains element of a single day

singleDay() is just a function that returns the element of a single date, that's it for the calendar logic and to finish off things we have to add a useEffect to change the displayed month on the calendar when prev or next button is clicked.

useEffect to change display month

And finally, we have arrived at the end. This calendar would be enough for a simple date selection calendar, and you can change the loops(while and for) and inline-styles as per your needs and requirement.

--

--

Vibin VS
0 Followers

A normal developer who wants to do his best