React Date Range Picker Component In Spfx

Introduction

 
The react-dates is a plugin written in React.js to initialize the React Date range picker component in React forms.
 
Open a command prompt. Create a directory for the SPFx solution.
 
md spfx-ReactDateRange
 
Navigate to the above-created directory.
 
cd spfx-ReactDateRange
 
Run the Yeoman SharePoint Generator to create the solution.
 
yo @microsoft/sharepoint
 
Solution Name
 
Hit Enter to have the default name (spfx-ReactDateRangein this case) or type in any other name for your solution.
Selected choice - Hit Enter
 
Target for the component
 
Here, we can select the target environment where we are planning to deploy the client web part; i.e., SharePoint Online or SharePoint OnPremise (SharePoint 2016 onwards).
 
Selected choice - SharePoint Online only (latest).
 
Place of files
 
We may choose to use the same folder or create a subfolder for our solution.
 
Selected choice - same folder.
 
Deployment option
 
Selecting Y will allow the app to be deployed instantly to all sites and be accessible everywhere.
 
Selected choice - N (install on each site explicitly).
 
Permissions to access web APIs
 
Choose if the components in the solution require permission to access web APIs that are unique and not shared with other components in the tenant.
 
Selected choice - N (solution contains unique permissions)
 
Type of client-side component to create
 
We can choose to create a client-side web part or an extension. Choose the web part option.
 
Selected choice - WebPart
 
Web part name
 
Hit Enter to select the default name or type in any other name.
 
Selected choice - ReactDateRangePicker
 
Web part description
 
Hit Enter to select the default description or type in any other value.
 
Framework to use
 
Select any JavaScript framework to develop the component. Available choices are - No JavaScript Framework, React, and Knockout.
 
Selected choice - React
 
The Yeoman generator will perform a scaffolding process to generate the solution. The scaffolding process will take a significant amount of time.
 
Once the scaffolding process is completed, lock down the version of project dependencies by running the below command,
 
npm shrinkwrap
 
In the command prompt, type the below command to open the solution in the code editor of your choice.
 
NPM Packages used,
  1. npm install --save react-dates  
  2. npm i moment 
Necessary imports,
  1. import * as Moment from 'moment';  
  2. import 'react-dates/initialize';  
  3. import 'react-dates/lib/css/_datepicker.css';  
  4. import { DateRangePicker, SingleDatePicker, DayPickerRangeController } from 'react-dates';  
To initialize DateRangePicker component, insert the below tag in render method, 
  1. <DateRangePicker/>  
To set Max and Min date use the following code as a sample
  1. public  isOutsideRange = day =>day.isAfter(Moment().add(10, "days")) || day.isBefore(Moment().subtract(1, "days"));  
To adjust arrow mark hidden in ui element use the below method
  1. (document.querySelector(".DateRangePickerInput_arrow_svg") as HTMLDivElement).style.padding='0 0 0 20px';  
 In this plugin we have lot of daterangepicker components as per different needs:
  • DateRangePicker (DRP)
  • SingleDatePicker (SDP)
  • DayPickerRangeController
  • DayPickerSingleDateController
  • DayPicker 
  • PresetDateRangePicker
For detailed documentation visit hereand here
 
Full Code
 
in ReactDateRangePicker.tsx
  1. import * as React from 'react';  
  2. import * as Moment from 'moment';  
  3. import { IReactDateRangePickerProps } from './IReactDateRangePickerProps';  
  4. import 'react-dates/initialize';  
  5. import 'react-dates/lib/css/_datepicker.css';  
  6. import { DateRangePicker, SingleDatePicker, DayPickerRangeController } from 'react-dates';  
  7. export interface IDateRangeState {        
  8.   startDate: any;  
  9.   endDate: any;  
  10.   focusedInput: any;    
  11. }   
  12. const divStyle = {  
  13.   padding: '0 0 0 20px'  
  14. };  
  15.   
  16. export default class ReactDateRangePicker extends React.Component<IReactDateRangePickerProps, IDateRangeState> {  
  17.   constructor(props) {  
  18.     super(props);  
  19.     this.state = {  
  20.       startDate: null,  
  21.       endDate: null,  
  22.       focusedInput: null,  
  23.     };  
  24.     this.isOutsideRange = this.isOutsideRange.bind(this);  
  25.   }  
  26.  public  componentDidMount(){  
  27.     (document.querySelector(".DateRangePickerInput_arrow_svg") as HTMLDivElement).style.padding='0 0 0 20px';  
  28.   
  29.   }  
  30.  public  isOutsideRange = day =>day.isAfter(Moment().add(10, "days")) || day.isBefore(Moment().subtract(1, "days"));  
  31.   
  32.   public render(): React.ReactElement<IReactDateRangePickerProps> {  
  33.    // const {focusedInput, startDate, endDate} = this.state;  
  34.     return (   
  35.       <div>  
  36.  <DateRangePicker  
  37.  regular={true}  
  38.  anchorDirection="left"  
  39.  block={true}  
  40.  customArrowIcon={null}  
  41.  customCloseIcon={null}  
  42.  customInputIcon={null}  
  43.  disabled={false}  
  44.  enableOutsideDays={true}  
  45.  endDatePlaceholderText="End"  
  46.  startDatePlaceholderText="Start"  
  47.  horizontalMargin={0}  
  48.  isRTL={false}  
  49.  keepOpenOnDateSelect={false}  
  50.  minimumNights={2}  
  51.  monthFormat="MMMM YYYY"  
  52.  navNext={null}  
  53.  navPosition="navPositionTop"  
  54.  navPrev={null}  
  55.  showClearDates={true}  
  56.  showDefaultInputIcon={true}  
  57.  displayFormat={() => "DD/MM/YYYY"}  
  58.  numberOfMonths={2}  
  59.  daySize={50}  
  60.  //withPortal={true}  
  61. isOutsideRange={this.isOutsideRange}  
  62. // isDayBlocked={ () => true}  
  63.      //isDayHighlighted={ () => true}  
  64.           startDateId="startDate"  
  65.           endDateId="endDate"  
  66.           startDate={this.state.startDate}  
  67.           endDate={this.state.endDate}  
  68.           onDatesChange={({ startDate, endDate }) => { this.setState({ startDate, endDate });}}  
  69.           focusedInput={this.state.focusedInput}  
  70.           onFocusChange={(focusedInput) => { this.setState({ focusedInput });}}  
  71.         />  
  72.       </div>  
  73.     );  
  74.   }  
  75. }  
 Available Properties
  1. regular - size of the picker
  2. small -size of the picker 
  3.  anchorDirection - direction of the picker 
  4.  block -fixed width of the picker
  5.  customArrowIcon -customized Arrow Icon
  6.  customCloseIcon -customized Close Icon
  7.  customInputIcon=customized Input Icon
  8.  disabled -to disable the picker
  9.  enableOutsideDays -enabling outside days
  10.  endDatePlaceholderText -Placeholder for end date
  11.  startDatePlaceholderText -Placeholder for start date
  12.  horizontalMargin -Margin from horizontal direction
  13.  isRTL -useful for arabic lang,to open picker in right side
  14.  keepOpenOnDateSelect - after clicking both dates picker never disappear
  15.  minimumNights - how much days want to selected as mandatory
  16.  monthFormat -format of month
  17.  displayFormat - display format whether as dd/mm/yy and etc...
  18.  numberOfMonths={2}
  19.  daySize -how long days need to visible from start and end date
  20.  withPortal - open as full indexed view
  21. isOutsideRange - to set min and max date to visible
  22. isDayBlocked - to blocking the days
  23. isDayHighlighted=to highlight the days
  24. startDateId=html id for start date 
  25. endDateId=html id for end date
  26. startDate=default value for start date
  27. endDate=default value for enddate
  28. onDatesChange -date change event
  29. onFocusChange -focus change event
and a lot more options are available as per the picker you have choosen
 

Event Types

 
onDatesChange - sets the value to the state when the Date is changed.
  1. onDatesChange = {({ startDate, endDate }) => { this.setState({ startDate, endDate });}}   
onFocusChange - sets the value to the state when the Focus is changed.
  1. onFocusChange = {(focusedInput) => { this.setState({ focusedInput });}}   
Sample Output
 
React Date Range Picker Component In Spfx
 

Conclusion

 
Hence we learned about initializing React Date Range Picker component in Spfx forms using react-dates plugin. I hope this helps someone. Happy coding :)