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

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

  • What is React-Calendar?
  • Create a React project
  • Add a Calendar using React-Calendar
  • Design your calendar
  • Select a date range
  • Customize the React – Calendar

What is React-Calendar?

React-calendar is a simple Calendar library that provides the ability to select days, months, years, and even decades. It also supports date range selection and a variety of languages for more complex usage cases.

Because React-Calendar doesn’t rely on moment.js, it’s a very flexible and versatile library that you can use in almost any application.

Create a React project

Let’s Create a new reaction item for this tutorial using the Create React App. Make sure you have Node.js≥ V10.16 and NPM ≥ V5.6 installed on your machine.

To create a new project, run the following command.

npx create-react-app calendar-example

Copy the code

Now, use NPM to add the React-Calendar library to our project.

npm install react-calendar

Copy the code

Now we have a basic setup. Remove the basic template code added by the Create React App, and let’s get started.

Add a Calendar using 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 the app.js file. The file will look like this.

// 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;

Copy the code

Here, we add a Calendar component to our app.js file and add two attributes to it. We create a state that stores dates and pass the current Date as its initial value using a JavaScript Date object.

With this basic structure in place, our initial calendar will look something like this.

The basic React calendar.

If you look at the code in the app.js file, we created a state called Date and passed it as a value to the Calendar component. Another item, onChange, is passed to Calendar, which sets the date’s state to the value the user clicks.

The initial value passed to the calendar is the current date. When the user clicks on the calendar, its value is set to the user’s selection. For this application, we print the date value below the calendar.

Design your calendar

We have completed a very basic calendar implementation. But as you can see, the styling hasn’t been applied to the calendar yet, so it looks pretty boring.

React-calendar provides a few default styles that you can apply by importing its style sheet. To do this, add the following line to your app.js file.

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

After applying the style, the calendar will look like this.

React Calendar with default style.

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

Select a date range

Consider a use case where you need to provide some data within a custom date range. The user selects the range of dates they want, and you can do it this way and then do something else. React-calendar supports this functionality very effectively.

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

The modified app.js will look like this.

// 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;Copy the code

To enable the date range functionality, we pass the selectRange item to our Calendar component. The default value for selectRange is false. With this item enabled, React-Calendar returns an array with two dates: the start date and the end date. The selection range is highlighted to inform the user of the selection.

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

React calendar with selected date range.

Customize the React – Calendar

Now that we’ve mastered the react-Calendar’s most useful features, let’s dig a little deeper and explore ways you can customize your Calendar.

**defaultValue**

DefaultValue this item allows you to set a default selected value. This item also supports 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 the start and end date values.

You can add defaultValue like this.

// 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>
  );
}

Copy the code

**defaultView**

This item is used to set the date view of the calendar. By default, it is set to month. Therefore, if this item is missing, the calendar is displayed as a month view.

DefaultView provides four options: month, year, decade, and century. Even if the item is set to a certain value, you can still navigate between different dates/months.

Here’s how to implement defaultView.

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

Copy the code

This item will change the initial rendering of the calendar to look like this.

React calendar with decade view.

maxDateminDate

If you don’t want the user to select a date after a certain date, you can prevent this action by adding a maxDate item to the calendar. As you can probably guess, the minDate item has a limit on how early the user can choose to start.

If the application has date ranges enabled, the user may choose a date later than maxDate or earlier than minDate. React-calendar prevents this by passing only the values of maxDate or minDate.

// 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
/>

Copy the code

maxDetailminDetail

The maxDetail and minDetail items are important to limit the granularity of the calendar. MaxDetail defines the maximum detail that the user can see. If the maxDetail value is set to year, the user can see the details of one year in the calendar at a time.

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

// calendar component

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

Copy the code

Here is an example of maxDetail and minDetail.



NextPrevThe label

The Next and Prev tags enable you to define the names of buttons to navigate between views in the calendar. You can also use the aria-label attribute to make it accessible.

Is used to change the next value prop nextLabel, nextAriaLabel, next2Label, and next2AriaLabel. You can add any string here, or you can set it to null if you want to disable this navigation.

These properties are similar to prev button, only the prev is a prefix, such as: prevLabel, prevAriaLabel, prev2Label, prev2AriaLabel, and so on.

After adding the Next and Prev tags, the code will look like this.

// 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'
/>

Copy the code

conclusion

React-calendar is a great library that provides a lot of flexibility in implementation. It is highly customizable and relies on local JavaScriptDate objects, which makes React-Calendar easy to implement in any application.

Go to the official documentation for some complex examples and use cases of the React-Calendar. I hope this tutorial leaves you with the basics you need to implement and customize The React-Calendar to suit your app and its audience.

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

The Postreact-Calendar tutorial: Creating and customising a simple Calendar, first appeared on The LogRocket blog.