GithubHelp home page GithubHelp logo

shahabyazdi / react-multi-date-picker Goto Github PK

View Code? Open in Web Editor NEW
725.0 4.0 87.0 44.01 MB

a simple React datepicker component for working with gregorian, persian, arabic and indian calendars

Home Page: https://shahabyazdi.github.io/react-multi-date-picker/

License: MIT License

JavaScript 89.55% CSS 10.45%
react calendar datepicker arabic gregorian indian hindi multi date picker

react-multi-date-picker's Introduction

DatePicker

Simple React datepicker component for working with gregorian, persian, arabic and indian calendars with the ability to select the date in single, multiple, range and multiple range modes.

date picker

Layouts

You can change the appearance of the datepicker to prime or mobile by importing css files from the styles folder.

date picker layouts

Plugins

Ability to further customize the calendar and datepicker by adding one or more plugins.

date picker plugins all in one

Installation

npm i react-multi-date-picker

Demo

Usage

import React, { useState } from "react";
import DatePicker from "react-multi-date-picker";

export default function Example() {
  const [value, setValue] = useState(new Date());

  return <DatePicker value={value} onChange={setValue} />;
}

Browser (non react-app)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>React Multi Date Picker</title>
  </head>
  <body>
    <span>Calendar Example :</span>
    <div id="calendar"></div>

    <span>DatePicker Example :</span>
    <div id="datePicker"></div>

    <span>Plugins Example :</span>
    <div id="datePickerWithPlugin"></div>

    <!-- Ract -->
    <script src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>

    <!-- DatePicker and dependencies-->
    <script src="https://cdn.jsdelivr.net/npm/date-object@latest/dist/umd/date-object.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/react-element-popper@latest/build/browser.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/react-multi-date-picker@latest/build/browser.min.js"></script>

    <!-- Optional Plugin -->
    <script src="https://cdn.jsdelivr.net/npm/react-multi-date-picker@latest/build/date_picker_header.browser.js"></script>

    <script>
      const { DatePicker, Calendar } = ReactMultiDatePicker;

      ReactDOM.render(
        React.createElement(Calendar),
        document.getElementById("calendar")
      );

      ReactDOM.render(
        React.createElement(DatePicker),
        document.getElementById("datePicker")
      );

      ReactDOM.render(
        React.createElement(DatePicker, {
          plugins: [React.createElement(DatePickerHeader)],
        }),
        document.getElementById("datePickerWithPlugin")
      );
    </script>
  </body>
</html>

Available props

Name Type Default Availability (DatePicker/ Calendar)
value Date, DateObject , String, Number or Array new Date() both
ref React.RefObject both
multiple Boolean false (true if value is Array) both
range Boolean false both
onlyMonthPicker Boolean false both
onlyYearPicker Boolean false both
format String YYYY/MM/DD both
formattingIgnoreList Array both
calendar Object gregorian both
locale Object gregorian_en both
mapDays Function both
onChange Function both
onPropsChange Function both
onMonthChange Function both
onYearChange Function both
onFocusedDateChange Function both
digits Array both
weekDays Array both
months Array both
showOtherDays Boolean false both
minDate Date, DateObject, String or Number both
maxDate Date, DateObject, String or Number both
disableYearPicker Boolean false both
disableMonthPicker Boolean false both
disableDayPicker Boolean false both
zIndex Number 100 both
plugins Array [] both
sort Boolean false both
numberOfMonths Number 1 both
currentDate DateObject both
buttons Boolean true both
renderButton React.ReactElement or Function both
weekStartDayIndex Number both
className String both
readOnly Boolean false both
disabled Boolean false both
hideMonth Boolean false both
hideYear Boolean false both
hideWeekDays Boolean false both
shadow Boolean true both
fullYear Boolean false both
displayWeekNumbers Boolean false both
weekNumber String both
weekPicker Boolean false both
rangeHover Boolean false both
monthYearSeparator String "," for LTR locales, "،" for RTL locales both
formatMonth Function undefined both
formatYear Function undefined both
highlightToday Boolean true both
style React.CSSProperties {} both
headerOrder Array ["LEFT_BUTTON", "MONTH_YEAR", "RIGHT_BUTTON"] both
onOpen Function DatePicker
onClose Function DatePicker
onPositionChange Function DatePicker
containerClassName String DatePicker
arrowClassName String 0 DatePicker
containerStyle React.CSSProperties DatePicker
arrowStyle React.CSSProperties 0 DatePicker
arrow Boolean or React.ReactElement true DatePicker
animations Array false DatePicker
inputClass String DatePicker
name String DatePicker
id String DatePicker
title String DatePicker
required Boolean DatePicker
placeholder String DatePicker
render React.ReactElement or Function DatePicker
inputMode String DatePicker
scrollSensitive Boolean true DatePicker
hideOnScroll Boolean false DatePicker
calendarPosition String "bottom-left" DatePicker
editable Boolean true DatePicker
onlyShowInRangeDates Boolean true DatePicker
fixMainPosition Boolean false DatePicker
fixRelativePosition Boolean false DatePicker
offsetY Number 0 DatePicker
offsetX Number 0 DatePicker
mobileLabels Object DatePicker
portal Boolean DatePicker
portalTarget HTMLElement DatePicker
onOpenPickNewDate Boolean true DatePicker
mobileButtons HTMLButtonElement[] [] DatePicker
dateSeparator string '~' in range mode, ',' in multiple mode DatePicker
multipleRangeSeparator string ',' DatePicker
typingTimeout string 700 DatePicker

Calendars & Locales

Click here to see the descriptions.

Calendars Gregorian Persian (Solar Hijri) Jalali Arabic (Lunar Hijri) Indian
/calendars/gregorian /calendars/persian /calendars/jalali /calendars/arabic /calendars/indian
Locales English /locales/gregorian_en /locales/persian_en /locales/persian_en /locales/arabic_en /locales/indian_en
Portuguese - BRAZIL /locales/gregorian_pt_br - - - -
Farsi /locales/gregorian_fa /locales/persian_fa /locales/persian_fa /locales/arabic_fa /locales/indian_fa
Arabic /locales/gregorian_ar /locales/persian_ar /locales/persian_ar /locales/arabic_ar /locales/indian_ar
Hindi /locales/gregorian_hi /locales/persian_hi /locales/persian_hi /locales/arabic_hi /locales/indian_hi

Of course, you can customize the names of the months and days of the week in both the calendar & input by using the months and weekDays Props.

Also, you can create a custom Calendar and Locale:

react-multi-date-picker's People

Contributors

andre-byrne avatar dariushstony avatar enzowu479 avatar juanruben avatar rkaufman13 avatar sanjarcode avatar shahabyazdi avatar shahriarkh avatar thebestmoshe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

react-multi-date-picker's Issues

Use Range and MultiPicker with onlyMonth option

Hello

I just started using this picker today, and it is fantastic. I was just wondering if it is possible to create range options for months as well as multi picker for months also.

So I guess you could have

12/2020 - 03/2021 for range

09/2020, 10/2020, 02/2021 for multi picker select

I have made various iterations in our storybook but it seemed like multi and range was only an option for the day calendar.

Hope this is possible.

How to disable the current date selection on calendar open?

In single mode, when I click an input and trigger the calendar open, the current date is always selected on default if the input value is empty.
Is there a way to disable this feature, and make the input value remain empty until the user select one?

weekDays, months type problem

  • how it is now in your code:

index.d.ts => weekDays?: [string[]],
months?: [string[]],
image
image
image

and if if chose code like this project will build, but in calendar i will not see my data:
image
image
image

  • how it work in my case if i change it:

index.d.ts => weekDays?: string[],
months?: string[],
1
2
3

Missing translatable labels in plugins

Hi, it would be really good if we could provide the translated labels to your plugins (e.g. the toolbar).
I saw that you started to handle this by taking the locale from the state, but it only works for the translations you implemented.
Instead I would foresee 3 props to provide the right label for each button, like you did for the weeks and months in the base library.

Anyway, really great job, I'm surprised your library is not used more than that (according to npmtrends).

Calendar skips one month when navigating between months.

Steps to reproduce the issue:

  1. Select a range of 29 days(Let say from Jan 1 to Jan 29).
  2. Then click okay.
  3. Again click the calendar and try to navigate to Feb now the calendar automatically takes you to March.

Note:

  1. When we select less than 29 days then we cannot reproduce the issue.

Close picker

How to close date picker with today onClick event in toolbar? and by the way, thanks for this great library :))

How to get the value of multiple date picker with custom input component?

Hello, is there a way to set the state from the value of the multiple date picker with a custom component?

I have this in my form component:

const [dates, setDates] = React.useState([]);

<DatePicker
  multiple
  plugins={[
    <DatePanel />
  ]}
  type="custom"
  render={<DateInput />}
  onChange={setDate}
  value={date}
/>
const DateInput = ({ openCalendar, stringDates, handleValueChange }) => (
  <TextField
    onFocus={openCalendar}
    value={stringDates.join(', ')}
    onChange={handleValueChange}
  />
);

But the value I get in my date state are just event objects. Can somebody help, please?

The 'Getting Started' documentation throws a type error

import React, { useState } from "react";
import DatePicker from "react-multi-date-picker";

export default function Example() {
  const [value, setValue] = useState(new Date());

  return <DatePicker value={value} onChange={setValue} />;
}

This copy/paste from the getting-started documentation throws a type error:

Type 'Dispatch<SetStateAction<Date>>' is not assignable to type '(selectedDates: DateObject | DateObject[]) => void'.
  Types of parameters 'value' and 'selectedDates' are incompatible.
    Type 'DateObject | DateObject[]' is not assignable to type 'SetStateAction<Date>'.
      Type 'DateObject' is not assignable to type 'SetStateAction<Date>'.
        Type 'DateObject' is missing the following properties from type 'Date': toDateString, toTimeString, toLocaleDateString, toLocaleTimeString, and 34 more.  TS2322

Is Date meant to be compatible, or do I have to use the additional date library you've built?

i need help

how i can handle "changeMonth" event?
image
image
i want to know what month is current?

[Question] How to add multiple onChange events in DatePicker?

import React, { useState } from "react"
import { DatePicker } from "react-multi-date-picker"

type DateProps = {
    updateDate : (date : Date) => void,
}

export function DateTimePIcker = (props : DateProps) => {
 const [date, setDate] = useState(new Date())

  return (
    <DatePicker 
         value={date}
         onChange={setDate}     // onChange={props.updateDate}
    />
  )
}

In the above example, if onChange is set to setDate, then whenever the date is changed by the user, it updates the state. If onChange is set to props.updateDate, then it updates the preset value in a parent component

Now, how to update both setValue and props passed at the same time?

I tried the below but they didn't work -

onChange={setDate && props.updateDate}

using multiple event handlers,

onChange={() => {
        eventHandler1()
        eventHandler2()
}}

const eventHandler1 = (date) => setDate(date)
const eventHandler2 = () => props.updateHardDeadline

DatePicker component onChange function does not update internal state.

Line 473, within date_picker.js, passes the internal state variable of "date" into the onChange user-defined function (passed in as a property); however, it fails to do anything with the function.

I wrote a function that is referenced within my onChange function definition. Below is the onChange property value, alongside the function I have created:

//Passing in fat arrow function via JSX property
onChange={(dates) => {selectLatestMonthDate(dates)}}

//onChange property will call the below function, when referenced within the DatePicker component.
//This function allows for the selection of multiple dates, but will only allow the user to select one date per
//month - maintain the latest date selected.
function selectLatestMonthDate(dates) {
dates = dates.filter(date => {
return dates.find(otherDate => {
return Number(otherDate.day) > Number(date.day)
&& Number(otherDate.month) == Number(date.month);
}) == undefined;
});
}

I have confirmed that DatePicker is calling my function, via a reference to the onChange property, and passing in an array of DateObjects (representing days that I have selected within the DOM). The problem is that my function, which overwrites the date array by removing some elements from the array, is not passed to the "setDate" state mutator within DatePicker. "SetDate" is called on line 469 - before the onChange call.

This is preventing me from modifying the date state via my onChange function. I cannot extend the behavior of multiple selection. Perhaps the "setDate" state reference can be moved to line 474, so that modifications within the onChange function are considered. This will make it very easy for developers to customize the multiple-select behavior, through onChange.

Otherwise, if this change is not made, I see no other way of modifying the state of this "stateless" component. The only other solution, would be to move to ES6 classes.

Thanks for your help.

[Feature] Ability to remove 'seconds' from time picker

Problem - The time picker plugin when used in the date-picker, creates the ability to add time but most of the times, we don't really need 'seconds' input in practical cases. I tried removing "SS" from Date Picker's format prop (format = "D MMMM YYYY, hh:mm A") but it only removes seconds from the date picker's input label but doesn't remove the second's input from time-picker

Solution -

image

So there should be a custom prop for , something like,

<TimePicker
isSeconds = false //A custom prop which removes seconds input field
>

or 

<TimePicker
format="HH:MM" //custom format to remove seconds. (In this case, it should also override the main picker's format)
>

DatePanel not working along with multiple selection

Hi, I have this component

<Calendar onlyShowInRangeDates={true} minDate={new Date()} value={selectedDates} onChange={setSelectedDates} plugins={[<DatePanel />]} multiple sort >

And it's crashing with the following output
Uncaught TypeError: (P || O).map is not a function
The above error occurred in the <E> component:

It stops crashing if y delete either the plugin or multiple prop

[Bug] DatePicker is not mobile responsive when used with TimePicker in default position (placed right side)

DatePicker when used with an Analog_time_picker, is mobile-friendly whereas when DatePicker is used with time_picker, it doesn't display properly on small screens.

image
Figure-1 (Displays properly)

image
Figure-2 (Doesn't display properly)

In the above images, we can see that when a datePicker is used with an Analog Time Picker displays properly but when used with a timePicker, cuts off the right side content

Code used -

import React, { useState } from "react";
import DatePicker, { DateObject } from "react-multi-date-picker";
// import TimePicker from "react-multi-date-picker/plugins/analog_time_picker";
import TimePicker from "react-multi-date-picker/plugins/time_picker";

export default function App() {
  let [date, setDate] = useState(new DateObject());

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <DatePicker
        value={date}
        onChange={setDate}
        calendarPosition="bottom-center"
        plugins={[<TimePicker hideSeconds />]}
      />
    </div>
  );
}

Actions to replicate the scenario -

  1. Go to this CodeSandbox
  2. In the right-side preview panel, beside the URL container, click on the "Open in new window" icon
  3. Preview opens in a new window. Right Click > Inspect > choose a mobile (like iPhone X)

multiple = {false} not working

const FormMultipleDatePicker: FunctionComponent = ({
displayName, name, placeholder, menuPortalTarget, minDate, maxDate,
className="", asterisk = true, variant="", isEdit, isMultiDatePickerDisabled = false,
placeHolderText = ""
}) => {
const {errors, control} = useFormContext();
// @ts-ignore
return <FlexColumn className={className + " px-2 mb-3"}>
{displayName}{asterisk? * :''}

<Controller
control={control}
name={name}
placeholder={placeholder}
menuPortalTarget={menuPortalTarget}
render={({onChange, value}) => (
isEdit ?
:

)}
/>

{errors[name] && errors[name].message}

};

in this code if i put multiple={false} the date picker is still allowing user to select multiple dates. is this a bug in the library itself. iam using datepicker with react-hookforms and controller

Custom Dates panel

Hi Shahab,

May I ask that can I add other event on dates panel?
For example, click certain date, it will do something.

How to set two months view in range date picker

Hi
Thanks for your perfect module. I am currently working on this module in my web application, And it's working great, but I need to show two months instead of one in range date picker.
How to display two months to selecting the range date?

Best regards

Implement a prop that blocks the selection of dates

Will be great to have the possibility to block the selection of out of scope dates, in a similar way that react-datepicker has.

  • minDate
  • maxDate

This way we could block the user the selection of dates outside the specified range (Very useful when you want to avoid the user picks a date in the past).

سلام اقای شهاب یزدی

اقای یزدی میشه یه راهنمایی بکنید چجوری میتونم لیست شهر ها و استان ها را در ری اکت بنویسم
؟

2month

hi
is it possible to show info for 2month to customer?

[Bug] Styling days creates empty boxes for the last few dates in the calendar month

In the documentation in map days, under 'Styling Days', there is an example on how to do custom styling.

Problem - Selecting the last few dates in the months creates empty styled boxes in the upcoming month. This applies to -> No of empty boxes at the start of the upcoming month == number of dates at the end of present month

Example -

image

In the above example, I have selected the date "May 30"

image

Here, it can be observed that an empty box is formed in the following month at the start of dates (under sunday)

MinDate is not working with DatePanel plugin

I want to disable previous dates in the calendar so I am using minDate prop.
image

Then I'm getting error -

image

But when I remove minDate prop, while using DatePanel plugin, everything works fine

Reset date picker to empty date in mobile.

Hi. Not sure if this is a bug as such. This seems to be for a mobile implementation.

We are trying to create a version of the DatePicker where we filter data based on the input date (using a month calendar) but we're also trying to implement a reset/clear all function. We reset the trigger button property, remove the current selected date and use placeholder text.

The issue is that the next time the calendar is launched the previously selected date is still active.

Example:
Select May 2019.
Execute Clear All.
Open new DatePicker, selected date is still shown as May 2019.

I thought there was a selectedDate prop (which was different to the DatePicker value prop, but I can't see it now.

I believe on the desktop version we can use an input trigger and empty this value which seems to clear the current selected date.

TIA

RunKit Issue

I'm trying to use RunKit to demonstrate a problem with the the DatePicker (it has to do with using the datepanel in mobile mode with a mininum selection date). RunKit, however, returns the error...

message: "Unexpected identifier"
SyntaxError Prototype

...for the default demo code at https://npm.runkit.com/react-multi-date-picker (linked to from the react-mult-date-picker npm page):

require("react/package.json"); // react is a peer dependency. 

require("react-dom/package.json"); // react-dom is a peer dependency. 
var reactMultiDatePicker = require("react-multi-date-picker")

Any idea why?

Date Panel Width

When I have the date format to show the day of the week and date it takes multiple lines. How can I widen the date panel to prevent this?

The date panel does not update when using both a minimum selection date and mobile mode

Issue: The date panel does not update when using both a minimum selection date and mobile mode.

To reproduce the problem, please see:
https://codesandbox.io/s/datepanel-broken-with-mindate-when-ismobile-3i0cp?file=/src/App.js

I took a cursory look at the code and couldn't figure out how to fix this problem. Can you help or point me in a good direction?

<DatePicker
  value={bookingDates}
  onChange={(dateObjects) => {
    setBookingDates(dateObjects);
  }}
  multiple={true}
  plugins={[<DatePanel />]}
  className="rmdp-mobile" // Remove either this line (className="rmdp-mobile") or the next to fix the DatePanel
  minDate={today} // Remove either this line (minDate={today}) or the next to fix the DatePanel
/>

Children prop type is not defined for DatePicker and Calendar

Hello I have noticed that in demo page we are able to insert children elements inside of DatePicker and Calendar elements but seems like the type for children is not defined.
Therefore I am getting such error:
Type '{ children: string; multiple: true; plugins: Element[]; onChange: (v: any) => void; }' is not assignable to type 'IntrinsicAttributes & CalendarProps'. Property 'children' does not exist on type 'IntrinsicAttributes & CalendarProps'.

I can do PR for this if so...
Thanks

How to get the ref of DatePicker component

I added a button component as a child of the DatePicker component. Than I want to close the open DatePicker by pressing the button.
How can I invoke closeCalendar method or somehow forward the ref to your component?

Thank you in advance,
Best regards

Formatting issue when setting new value

I'm using Fullcalendar alongside your date picker. Here is my code

const [selectedDate, setSelectedDate] = useState(moment().toDate());

<DatePicker
        value={selectedDate}
        multiple={repeat}
        format='DD MMM YYYY'
        minDate={moment().toDate()}
        maxDate={moment().add(7, 'd').toDate()}
        style={styles.textfield}
        onChange={date => console.log(new Date(date[0]))}
 />

When I handle date click event in fullcalendar, and set new date, it fails. The error statement being...

TypeError: r.format is not a function

const handleDateEvent = (event) => {
        // event.date gives Sat Nov 28 2020 19:00:00 GMT+0530 (India Standard Time)
        const selDate = moment(event.date).valueOf()  
        setSelectedDate(selDate);  // throws error
};

However, if I do it like this, it sorta works, but renders unwanted date format as in " 2020-11-25T21:00:00+05:30 ", even though I have specified the format already.

 const handleDateEvent = (event) => {
        setSelectedDate(moment(event.date));
 };

Date panel not working in typescript

Hi,

React multi date picker , I'm using in typescript but that is getting error like this
image

and React multi date picker for typescript not available in NPM repo

isSameDate only works with DateObject() but not a native Date()

isSameDate method can be used to compare 2 dates and do something based on that, but it only works when compared to a DateObject() and not a Date()

Example -

if (isSameDate(date, new DateObject())) props.style.color = "green";
// this turns today's date in calendar to green color

if (isSameDate(date, new Date())) props.style.color = "green";
// this also should do  the same job but it doesn't

link to codesand box

Multi Date Functionality Display Issues in Latest version.

Hi Shahab, I've upgraded to the latest version ( 2.0.2 ) from 1.8.0. Here are my observations while using this package for our project.

  1. It would be better if multiple dates selected can be displayed in ascending order in the date field.
  2. If I use, a custom component, like MUI-Textfield as the input field, and select multiple dates, selected dates doesn't show in the field, but their value is being correctly taken.

Feel free to experiment in this Sandbox.

custom-tf
date-order

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.