React Date Range Picker Demo
This tutorial will teach you how to add a date Range picker to your react application using Airbnb react-dates an easy internationalizable, mobile-friendly* datepicker library for the web http://airbnb.io/react-dates.
A date range picker is an interactive dropdown that makes it easy to choose the date range from a calendar instead of typing it manually.
It’s a great way to avoid user errors because you can see the corresponding day of the week for each date. and Less input fields to verify ( 1 fields instead of 2 ) ,
* require a tweak that we will tackle in the responsive part
Let’s start !
Initialization
for the sake of this tutorial we will start by creating demo react application.
$ npx create-react-app react-daterangepicker-demo $ cd react-daterangepicker-demo/ $ npm start
Let’s Edit the App.js File to match the following structure :
We added the state that will contain startDate and endDate Object , their formatted string and then we will add the render HTML
Adding the react-dates library
Now lets start installing the React-Dates from Airbnb.io and the required library moment (Parse, validate, manipulate, and display dates and times )
$ npm install --save react-dates moment
let’s import the required scripts and styles:
...
import "react-dates/initialize";
import { DateRangePicker } from "react-dates";
import "react-dates/lib/css/_datepicker.css";
...
next step is to replace this comment {/* daterangepicker */} with the following code :
then add the hundleDateChange Function so we can update the date state and set the formatted dates :
the code then is the following :
Responsive Date Range Picker
Final step is to make the Daterangepicker responsive which means showing only one calendar instead of 2 in the small devices , in oder to do that we need to install react-responsive library (Media queries in react for responsive design)
$ npm install --save react-responsive
we will then import the script and do the following changes :
our final code will be :
Thank you for reading and Happy Coding
Demo repository on Github : https://github.com/achrafAa/react-daterangepicker-demo
Originally published at https://achrafaamri.com on May 27, 2020.