Create a calendar in React js

Manish Mandal
How To React
Published in
2 min readOct 1, 2020

Today I will discuss how to create a calendar in our React js project. The calendar is useful when you want to create some booking system or filter option which depends on a particular date. The best module I came across for implementing the calendar in the React js project is react-calendar by wojtekmaj. The UI of this module is great and it’s very easy to use and implement in our React js project. So let’s discuss how to implement that in our project.

Requirements

  1. Create and open your React js project.
yarn create react-app yourprojectname
cd yourprojectname

2. Install react-calendar and moment to your project.

yarn add react-calendar moment

3. Now import Calendar from react-calendar and also the CSS.

import Calendar from 'react-calendar'
import 'react-calendar/dist/Calendar.css';

4. Now call that Calendar tag inside return and run your project yarn start. Refresh your browser to see changes.

5. Now we will initialize our state using the javascript Date method. So now we first need to call our useState hook from React and initialize our state inside our functional component.

import React, {useState} from 'react'const [dateState, setDateState] = useState(new Date())

6. Now we will pass our dateState as props value to our Calendar tag and use the onChange method to update our dateState with the current selection. I have also created changeDate function to change our state and passed that to our onChange method.

//Change Date Method 
const changeDate = (e) => {
setDateState(e)
}
//Calendar Tag
<Calendar
value={dateState}
onChange={changeDate}
/>

7. We cannot directly render the dateState as it will lead to an Objects are not valid error. So now we will import the moment library to format our date and wrap our dateState with the moment method. Below is the full code with a demo. Note: For more detail on how to use moment you can visit my previous tutorial.

import moment from 'moment'{moment(dateState).format('MMMM Do YYYY')}

That’s it for today. Below are the live code and GitHub repository for reference.

--

--

Manish Mandal
How To React

Full Stack Developer | React JS | Next JS | Node JS | Vue JS | Wordpress. Connect with me https://www.linkedin.com/in/manishmandal21/