React-Calendar tutorial: Build and customize a simple calendar
Tags: react, javascript, webdev
Published: 2021-08-12 18:24:27

**Written by [Yogini Bende] (https://blog.logrocket.com/author/yoginibende/)** ✏️

Most real-world applications include a way to manage and manipulate dates. In such use cases, having a calendar is often the most effective solution.

In this tutorial, we’ll show you how to create a simple calendar in React using React-Calendar. We’ll cover the following with practical examples:

*   [What is React-Calendar?](#what-react-calendar)
*   [Creating a React project](#creating-react-project)
*   [Adding a calendar with React-Calendar](#adding-calendar-with-react-calendar)
*   [Styling your calendar](#styling-your-calendar)
*   [Selecting a date range](#selecting-date-range)
*   [Customizing React-Calendar](#customizing-react-calendar)

## What is React-Calendar?

[React-Calendar](https://github.com/wojtekmaj/react-calendar) is a simple calendar library that provides the ability to pick days, months, years, or even decades. It also supports date range selection and a variety of languages for more complex use cases.

Because React-Calendar is not dependent on `moment.js`, it’s a very flexible and versatile library that you can use in virtually any application.

## Creating a React project

Let’s create a fresh new react project for this tutorial using [Create React App](https://blog.logrocket.com/getting-started-with-create-react-app-d9314). Make sure you have [Node.js](https://nodejs.org/en/) ≥v10.16 and npm ≥v5.6 installed on your machine.

To create a new project, run the following command:

```bash
npx create-react-app calendar-example
```

Now, add the React-Calendar library to our project using npm:

```bash
npm install react-calendar
```

Now we have a bare-minimum setup. Remove the basic boilerplate code added by Create React App and let’s get started.

## Adding a calendar with React-Calendar

The first step is to add the calendar to our React app. Import the `Calendar` component from `react-calendar` and add it to `app.js` file. The file will look something like this:

```javascript
// App.js 

import { useState } from 'react';
import Calendar from 'react-calendar';
import './App.css';

function App() {
  const [date, setDate] = useState(new Date());

  return (
    <div className='app'>
      <h1 className='text-center'>React Calendar</h1>
      <div className='calendar-container'>
        <Calendar onChange={setDate} value={date} />
      </div>
      <p className='text-center'>
        <span className='bold'>Selected Date:</span>{' '}
        {date.toDateString()}
      </p>
    </div>
  );
}

export default App;
```

Here, we added a `Calendar` component to our `app.js` file and added two properties to it. We created a state to store a date and passed the current date as its initial value using JavaScript’s `Date` object.

With this basic structure ready, our initial calendar will look similar to this:

| ![Calendar With Dates On A Rectangular Grid In Black, White, And Grey](https://blog.logrocket.com/wp-content/uploads/2021/08/basic-react-calendar.png) | 
|:--:| 
| *Basic React Calendar.* |

If you check the code of the `app.js` file, we created a state named `date` and passed it as a value to the `Calendar` component. Another prop, `onChange`, is passed to `Calendar`, which sets the `date` state to the value clicked by the user.

The initial value passed to the calendar is the present date. When a user clicks the calendar, its value will be set to the user’s selection. For this application, we are printing the date value below our calendar.

## Styling your calendar

We’re done with the very basic calendar implementation. But as you can see, the styling is not yet applied to the calendar, so it looks pretty boring.

React-Calendar provides some default styling, which you can apply by importing its stylesheet. To do this, add the following line to your `app.js` file:

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

After applying the styling, calendar will look like this

![Calendar With Dates On A Square Grid In Black And White](https://blog.logrocket.com/wp-content/uploads/2021/08/default-styling-react-calendar.png)

If you want to add your own styling, you can override these classes and add your custom CSS properties.

## Selecting a date range

Consider a use case where you need to provide some data between a custom date range. The user selects their desired date range, which you can take and then do the rest of the operations. React-Calendar supports this feature very effectively.

Let’s take this use case and improve our application to select the date range. We will print the start and end of the range at the bottom of the calendar.

The modified `app.js` will look like this:

```javascript
// App.js

import { useState } from 'react';
import Calendar from 'react-calendar';
import 'react-calendar/dist/Calendar.css';
import './App.css';

function App() {
  const [date, setDate] = useState(new Date());

  return (
    <div className='app'>
      <h1 className='text-center'>React Calendar with Range</h1>
      <div className='calendar-container'>
        <Calendar
          onChange={setDate}
          value={date}
          selectRange={true}
        />
      </div>
      {date.length > 0 ? (
        <p className='text-center'>
          <span className='bold'>Start:</span>{' '}
          {date[0].toDateString()}
          &nbsp;|&nbsp;
          <span className='bold'>End:</span> {date[1].toDateString()}
        </p>
      ) : (
        <p className='text-center'>
          <span className='bold'>Default selected date:</span>{' '}
          {date.toDateString()}
        </p>
      )}
    </div>
  );
}

export default App;
```

To enable date range feature, we pass `selectRange` prop to our `Calendar` component. The default value of `selectRange` is false. After enabling this prop, React-Calendar returns an array with two dates: the start date and end date. The selected range is highlighted to make the user understand the selection.

After adding a date range, the calendar component will look like this:

| ![Calendar With A Range Of Dates Highlighted In Blue](https://blog.logrocket.com/wp-content/uploads/2021/08/date-range-react-calendar.png) | 
|:--:| 
| *React Calendar with selected date range.* |

## Customizing React-Calendar

Now that we have a handle on the most useful functionalities of React-Calendar, let’s dive a little deeper and explore the ways you can customize your calendar.

**`defaultValue`**

The `defaultValue` prop enables you to set a default selected value. This prop also supports the default date range selection. If you want to select a single date, you can pass a date object. Otherwise, you can pass an array containing start and end date values.

You can add `defaultValue` like this:

```javascript
// App.js

function App() {
  const [date, setDate] = useState([
    new Date(2021, 6, 1),
    new Date(2021, 6, 10),
  ]);

  return (
    <div className='app'>
      <h1 className='text-center'>React Calendar with Range</h1>
      <div className='calendar-container'>
        <Calendar
          onChange={setDate}
          selectRange={true}
          defaultValue={date}                                                     
        />
      </div>
    </div>
  );
}
```

**`defaultView`**

This prop is used to set the date view of the calendar. By default, it is set to month. So if this prop is missing, the calendar shows you a month view.

`defaultView` provides four options: month, year, decade and century. Even if this prop is set to some value, you can still navigate between different dates/months.

Here’s how to implement `defaultView`:

```javascript
// Calendar component
<Calendar
  onChange={setDate}
  selectRange={true}
  defaultView='decade'                                                    
/>
```

This prop will change the initial rendering of the calendar, making it look something like this:

| ![Calendar Showing Years 2021 through 2030](https://blog.logrocket.com/wp-content/uploads/2021/08/decade-view-react-calendar.png) | 
|:--:| 
| *React Calendar with a decade view.* |

**`maxDate` and `minDate`**

If you don’t want the user to select a date after a certain day, you can prevent this action by adding a `maxDate` prop to your calendar. As you can probably guess, the `minDate` prop sets a limit on how early a start date the user is allowed to select.

If the date range is enabled for the app, the user might be able to select the date that is later than the `maxDate` or earlier than the `minDate`. React-Calendar prevents this by passing the `maxDate` or `minDate` value only and nothing beyond that.

```javascript
// calendar component

<Calendar
  onChange={setDate}
  value={date}
  maxDate={new Date()} // will not allow date later than today
  minDate={new Date(2015, 6, 1)} // will not allow date before 1st July 2015
/>
```

**`maxDetail` and `minDetail`**

The `maxDetail` and `minDetail` props are important for restricting the granularity of the calendar. `maxDetail` defines the maximum amount of details the user can see. If the `maxDetail` value is set to **year**, the user can see details of a year in the calendar at a time.

Similarly, if `minDetail` is set to year, the user will not be able to see details beyond a given year.

```javascript
// calendar component

<Calendar
  onChange={setDate}
  value={date}
  maxDetail='year'
/>
```

Below is an example of `maxDetail` and `minDetail`:

![Max Detail Calendar Showing The Months In A Year And Min Detail Calendar Showing The Days In A Month](https://blog.logrocket.com/wp-content/uploads/2021/08/max-min-detail-react-calendar.png)

**`Next` and `Prev` labels**

The `Next` and `Prev` labels enable you to define the names of the buttons used to navigate between views in the calendar. You can also make this accessible using the `aria-label` attributes.

The props used to change the next values are `nextLabel`, `nextAriaLabel`, `next2Label`, and `next2AriaLabel`. You can add any string to this or you can set it to `null` if you want to disable this navigation.

These properties are similar for prev buttons except that prev is a prefix — e.g., `prevLabel`, `prevAriaLabel`, `prev2Label`, `prev2AriaLabel`, etc.

After adding the `Next` and `Prev` labels, the code will look like this:

```javascript
// calendar component

<Calendar
  onChange={setDate}
  value={date}
  nextLabel='month>>'
  nextAriaLabel='Go to next month'
  next2Label='year>>'
  next2AriaLabel='Go to next year'
  prevLabel='<<month'
  prevAriaLabel='Go to prev month'
  prev2Label='<<year'
  prev2AriaLabel='Go to prev year'
/>
```

## Conclusion

React-Calendar is a wonderful library that provides a lot of flexibility in its implementation. It is highly customizable and dependent on the native JavaScript `Date` object, which makes React-Calendar easy to implement in any application.

Head to the official documentation for some [complex examples and use cases for React-Calendar](https://github.com/wojtekmaj/react-calendar/wiki/Recipes). I hope this tutorial leaves you with the foundational knowledge you need to implement and customize React-Calendar to suit your app and its audience.

If you have any questions about using React-Calendar, feel free to ask them in the comment below.

---

## Full visibility into production React apps

Debugging React applications can be difficult, especially when users experience issues that are hard to reproduce. If you’re interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, [try LogRocket] (https://www2.logrocket.com/react-performance-monitoring).

[![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6v4gw3tgq2topvafgpgz.png)](https://www2.logrocket.com/react-performance-monitoring)[![LogRocket Dashboard Free Trial Banner] (https://blog.logrocket.com/wp-content/uploads/2017/03/1d0cd-1s_rmyo6nbrasp-xtvbaxfg.png)](https://www2.logrocket.com/react-performance-monitoring)

[LogRocket] (https://www2.logrocket.com/react-performance-monitoring) is like a DVR for web apps, recording literally everything that happens on your React app. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app's performance, reporting with metrics like client CPU load, client memory usage, and more.

The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.

Modernize how you debug your React apps — [start monitoring for free] (https://www2.logrocket.com/react-performance-monitoring).