How to Create Date Range Picker with Presets in React 18

Last Updated on by in React JS Tutorial

Date range picker allows users to select specific date ranges from a calendar component and serves the purpose of making users choose specific time spans for booking flights, hotel reservations, scheduling appointments, and much more. Presets are the small buttons within the date range picker, allowing users to select predefined dates or date ranges to make the ranged date selection.

In this tutorial, we will teach you how to create a date range picker calendar component and how to create and implement it in the React application using react-dates, moment, and React hooks.

React-dates is a popular plugin developed by Airbnb that offers tons of features to build a date selection calendar in React. It simplifies working with dates in React, expanding the functionality associated with date selection and manipulation within web applications.

It offers top-notch features to play around calendar component, supporting all major browsers, like Chrome, Firefox, and much more. It is highly customizable and offers tons of customization options, allowing you to alter the date range picker’s features and aesthetics based on specific requirement.

To know more checkout Airbnb Engineering’s official documentation of react-dates library.

Let’s understand how to build date range calendar and how to add presets to date range calendar in React.

Create React Project

Open the code editor, also open the command-prompt. If you have installed Node and Npm then run the given command to install a new app.

npx create-react-app my-react-app

As soon as you created the project, just enter into the project directory.

cd my-react-app

Install React Dates Dependency

We will install bootstrap, moment and react date-picker package using the given command.

npm i bootstrap moment

At the time of creating this tutorial, we are using React 18+ version. The react-datepicker is not compatible with React’s latest version.

To tackle such problem we are using the –legacy-peer-deps tag.

npm i react-dates --legacy-peer-deps

Create Component Files

Moreover, you have to create the components/ folder. You can now create as many component as you want.

Make sure to create components/DatePresets.js component using the below code.

import React from 'react'
function DatePresets() {
  return (
    <div></div>
  )
}
export default DatePresets

Create components/Calendar.js file using the below code:

import React from 'react'
function Calendar() {
  return (
    <div></div>
  )
}
export default Calendar

Add Preset to React Date Range Picker

To add presets to calendar component, insert the following code in components/DatePresets.js component file.

import React from "react";
import moment from "moment";
const DatePresets = (props) => {
  const { startDate, endDate, showDateFormat, handlePresets } = props;
  const today = moment();
  const presets = [
    {
      text: "Next Week",
      start: today,
      end: moment().add(1, "week"),
    },
    {
      text: "Next Month",
      start: today,
      end: moment().add(1, "month"),
    },
    {
      text: "Next 3 Months",
      start: today,
      end: moment().add(3, "month"),
    },
  ];
  return (
    <div className="p-3">
      {presets.map(({ text, start, end }) => {
        const isChosen =
          moment(start).format(showDateFormat) ===
            moment(startDate).format(showDateFormat) &&
          moment(end).format(showDateFormat) ===
            moment(endDate).format(showDateFormat);
        return (
          <button
            key={text}
            type="button"
            className={`btn btn-sm btn-dark ${
              isChosen ? "btn-success" : "btn-danger"
            }`}
            style={{ marginRight: 12 }}
            onClick={() => handlePresets(start, end)}
          >
            {text}
          </button>
        );
      })}
    </div>
  );
};
export default DatePresets;

Create Date Range Picker in React

The DateRangePicker is the module that we need, we also have to import DatePresets. You can pass the essential props and methods to add the date presets.

Add the code in the components/Calendar.js file.

import React, { useState } from "react";
import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";
import { DateRangePicker } from "react-dates";
import DatePresets from "./DatePresets";
export default function Calendar() {
  const dateFormat = "DD/MM/YYYY";
  const [startDate, setStartDate] = useState(null);
  const [dateEnd, setEndDate] = useState(null);
  const [dateInput, setDateInput] = useState(null);
  return (
    <div>
      <DateRangePicker
        startDate={startDate}
        startDateId="s_id"
        endDate={dateEnd}
        endDateId="e_id"
        onDatesChange={({ startDate, endDate }) => {
          setStartDate(startDate);
          setEndDate(endDate);
        }}
        focusedInput={dateInput}
        onFocusChange={(e) => setDateInput(e)}
        dateFormat={dateFormat}
        renderCalendarInfo={() => (
          <DatePresets
            startDate={startDate}
            endDate={dateEnd}
            dateFormat={dateFormat}
            handlePresets={(start, end) => {
              setStartDate(start);
              setEndDate(end);
            }}
          />
        )}
      />
      <div className="mt-3">
        <div>
          <strong>Start date: </strong>
          {startDate && startDate.format("ll")}
        </div>
        <div>
          <strong>End date: </strong>
          {dateEnd && dateEnd.format("ll")}
        </div>
      </div>
    </div>
  );
}

Register Component in App Js

Head over to App.js file; now in this file you have to first import the Dashboard component; also ensure that you added it inside the App() method.

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import Calendar from "./components/Calendar";
function App() {
  return (
    <div className="container mt-3">
      <h2 className="mb-3">React Date Range Picker with Presets Example</h2>
      <Calendar />
    </div>
  );
}
export default App;

View App in Browser

There is only one task left; that is to run the development server.

You have to use the given command to run the react app.

npm start

Here is the url that shows your app on the browser.

http://localhost:3000

How to Implement Preset in React Date Range Picker

Conclusion

In this tutorial, we have shown you how to incorporate presets to date range picker component using React js.

We learned how to configure a React project from scratch and build a date range picker component using react-dates and moment libraries.

❤️ Checkout Popular CSS Collection

Digamber - Author positronX.io

Digamber, the founder of PositronX, is a certified web developer with over 10 years of experience. He possesses a curiosity for learning new things and enjoys playing cricket on his days off.