React Calendar date picker

In this tutorial we will learn how to render a calendar with React using the react-calendar module.

Introduction

In this tutorial we will learn how to render a calendar with React using the react-calendar module. Besides many other features, this calendar allows us to pick the date and select a date range from a very user friendly interface. We will analyze both features in the sections below.

To install this module with NPM we simply need to send the following command:

npm install react-calendar

To check the many functionalities supported by the Calendar component we will be using in the code below, please check its list of props here. For a live demo, please check here.

I’ve setup my testing environment using Create React App. It’s a very simple way to get started developing with React without needing to manually setup a complex toolchain.

A simple example

We will start our code by the imports. We will need to import React and ReactDom, to write our components. We will also import the useState Hook, so we can add state to our functional component (to hold the picked date).

Besides that, we will import the Calendar component, from the package we have just installed.

import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import Calendar from 'react-calendar';

To use the default calendar look and feel, we also need to import the corresponding CSS styles.

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

After this, we will define a wrapper component that will render our calendar and also store the date changes resulting from the user interaction. I’ll be calling it MyCalendar, but you can call it however you prefer. We will be defining this component as a React function component, which is why we will need the useState hook.

function MyCalendar() {
   // component implementation
}

Then we will declare a new state variable to hold the selected date. We will call this variable date and call setDate to its update function. We will initialize this state variable to today’s date. For more information on how to declare a state variable, please check here.

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

We will also define a function that will be used as callback whenever the date value changes (when the user picks a new value). This function will simply set the state variable date to the newly picked value and also print it to the console.

const onDateChange = (newDate) => {
    setDate(newDate);
    console.log(newDate);
}

We will finish our component implementation by returning the Calendar component we have imported at the beginning of our code, after setting some of its props.

First, we need to set the value prop, which corresponds to the current calendar value. So, we should pass to this prop the date we are holding on our state. Note that the value we chose before when initializing the state variable will be the initial date that our calendar will display. Naturally, we can use an initial value other than today.

We will set the onChange prop to our onDateChange callback, so it is executed whenever a new date is picked.

We will also set the showNeighboringMonth prop to false. This prop controls whether days from previous or next month shall be rendered if the month doesn’t start on the first day of the week or doesn’t end on the last day of the week [1].

To finalize, we will set the locale prop. This corresponds to the locale that will be used in the calendar and it can be any IETF language tag. If not specified, it will use the Browser settings [1]. Since my Browser is in Portuguese, I’ll force this value to “en-US”.

return (
    <Calendar
        onChange={onDateChange}
        value={date}
        showNeighboringMonth={false}
        locale={"en-US"}
     />
);

The complete component can be seen below.

function MyCalendar() {

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

  const onDateChange = (newDate) => {
    setDate(newDate);
    console.log(newDate);
  }

  return (
      <Calendar
          onChange={onDateChange}
          value={date}
          showNeighboringMonth={false}
          locale={"en-US"}
        />
  );
}

To finalize, our MyCalendar component will be wrapped in a call to the render method of the ReactDOM object. I’m assuming the HTML file that will contain our app has an element called “root“.

ReactDOM.render(
    <MyCalendar />,
    document.getElementById('root')
);

The complete code can be seen below.

import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import Calendar from 'react-calendar';

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

function MyCalendar() {

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

  const onDateChange = (newDate) => {
    setDate(newDate);
    console.log(newDate);
  }

  return (
      <Calendar
          onChange={onDateChange}
          value={date}
          showNeighboringMonth={false}
          locale={"en-US"}
        />
  );
}

ReactDOM.render(
    <MyCalendar />,
    document.getElementById('root')
);

After compiling and serving the application, you should obtain a result like the one shown in figure 1. As can be seen, we obtain an interactive calendar with a nice look and feel. We can change the day and the corresponding value will be printed on the console.

Rendering the React Calendar component on the browser.
Figure 1 – Rendering the React Calendar component on the browser.

The GIF below exemplifies user interaction with the calendar. As can be seen, we can change the month and the year and also go to a year view where we can pick the month.

User interaction with the calendar component.
Figure 2 – User interaction with the calendar component.

Date Range selection

One additional feature supported by the Calendar component is allowing the user to select a date range. By default, this functionality is disabled but we can enable it by setting the selectRange prop to true [1].

In this case, the onChange callback will receive an array with two dates: the start of the range and the end of the range. This array is also the format that we shall pass as the value prop.

<Calendar
     onChange={onDateChange}
     value={date}
     showNeighboringMonth={false}
     locale={"en-US"}
     selectRange={true}
 />

The complete code can be seen below.

import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import Calendar from 'react-calendar';

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

function MyCalendar() {

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

  const onDateChange = (newDate) => {
    setDate(newDate);
    console.log(newDate);
  }

  return (
      <Calendar
          onChange={onDateChange}
          value={date}
          showNeighboringMonth={false}
          locale={"en-US"}
          selectRange={true}
        />
  );
}

ReactDOM.render(
    <MyCalendar />,
    document.getElementById('root')
);

Like before, after compiling and serving the React app, you should see the calendar component in your browser. In this case, we are now able to select a range of dates rather than just a single day, as shown in figure 3. Note that an array with two dates (initial and final date of the range) gets printed to the browser console when we do a selection.

Date range selection on the React Calendar component.
Figure 3 – Date range selection on the React Calendar component.

References

[1] https://www.npmjs.com/package/react-calendar

Leave a Reply

%d bloggers like this: