Coder Social home page Coder Social logo

wojtekmaj / react-daterange-picker Goto Github PK

View Code? Open in Web Editor NEW
509.0 6.0 62.0 6.67 MB

A date range picker for your React app.

Home Page: https://projects.wojtekmaj.pl/react-daterange-picker

License: MIT License

HTML 0.46% CSS 5.92% TypeScript 93.62%
react calendar date daterange daterange-picker

react-daterange-picker's Introduction

npm downloads CI

React-DateRange-Picker

A date range picker for your React app.

  • Pick days, months, years, or even decades
  • Supports virtually any language
  • No moment.js needed

tl;dr

  • Install by executing npm install @wojtekmaj/react-daterange-picker or yarn add @wojtekmaj/react-daterange-picker.
  • Import by adding import DateRangePicker from '@wojtekmaj/react-daterange-picker'.
  • Use by adding <DateRangePicker />. Use onChange prop for getting new values.

Demo

A minimal demo page can be found in sample directory.

Online demo is also available!

Consider native alternative

If you don't need to support legacy browsers and don't need the advanced features this package provides, consider using native date input instead. It's more accessible, adds no extra weight to your bundle, and works better on mobile devices.

<input aria-label="Date from" max={valueTo} min={minDate} type="date" />
<input aria-label="Date to" max={maxDate} min={valueFrom} type="date" />

Looking for a time picker or a datetime picker?

React-DateRange-Picker will play nicely with React-Date-Picker, React-Time-Picker and React-DateTime-Picker. Check them out!

Getting started

Compatibility

Your project needs to use React 16.3 or later. If you use an older version of React, please refer to the table below to find a suitable React-DateRange-Picker version.

React version Newest compatible React-DateRange-Picker version
≥16.8 latest
≥16.3 4.x
≥16.0 2.x

React-Calendar, on which React-DateRange-Picker relies heavily, uses modern web technologies. That's why it's so fast, lightweight and easy to style. This, however, comes at a cost of supporting only modern browsers.

Installation

Add React-DateRange-Picker to your project by executing npm install @wojtekmaj/react-daterange-picker or yarn add @wojtekmaj/react-daterange-picker.

Usage

Here's an example of basic usage:

import { useState } from 'react';
import DateRangePicker from '@wojtekmaj/react-daterange-picker';

type ValuePiece = Date | null;

type Value = ValuePiece | [ValuePiece, ValuePiece];

function MyApp() {
  const [value, onChange] = useState<Value>([new Date(), new Date()]);

  return (
    <div>
      <DateRangePicker onChange={onChange} value={value} />
    </div>
  );
}

Custom styling

If you want to use default React-DateRange-Picker and React-Calendar styling to build upon it, you can import them by using:

import '@wojtekmaj/react-daterange-picker/dist/DateRangePicker.css';
import 'react-calendar/dist/Calendar.css';

User guide

DateRangePicker

Displays an input field complete with custom inputs, native input, and a calendar.

Props

Prop name Description Default value Example values
autoFocus Automatically focuses the input on mount. n/a true
calendarAriaLabel aria-label for the calendar button. n/a "Toggle calendar"
calendarProps Props to pass to React-Calendar component. n/a See React-Calendar documentation
calendarIcon Content of the calendar button. Setting the value explicitly to null will hide the icon. (default icon)
  • String: "Calendar"
  • React element: <CalendarIcon />
  • React function: CalendarIcon
className Class name(s) that will be added along with "react-daterange-picker" to the main React-DateRange-Picker <div> element. n/a
  • String: "class1 class2"
  • Array of strings: ["class1", "class2 class3"]
clearAriaLabel aria-label for the clear button. n/a "Clear value"
clearIcon Content of the clear button. Setting the value explicitly to null will hide the icon. (default icon)
  • String: "Clear"
  • React element: <ClearIcon />
  • React function: ClearIcon
closeCalendar Whether to close the calendar on value selection. Note: It's recommended to use shouldCloseCalendar function instead. true false
data-testid data-testid attribute for the main React-DateRange-Picker <div> element. n/a "daterange-picker"
dayAriaLabel aria-label for the day input. n/a "Day"
dayPlaceholder placeholder for the day input. "--" "dd"
disableCalendar When set to true, will remove the calendar and the button toggling its visibility. false true
disabled Whether the date range picker should be disabled. false true
format Input format based on Unicode Technical Standard #35. Supported values are: y, M, MM, MMM, MMMM, d, dd. Note: When using SSR, setting this prop may help resolving hydration errors caused by locale mismatch between server and client. n/a "y-MM-dd"
id id attribute for the main React-DateRange-Picker <div> element. n/a "daterange-picker"
isOpen Whether the calendar should be opened. false true
locale Locale that should be used by the date range picker and the calendar. Can be any IETF language tag. Note: When using SSR, setting this prop may help resolving hydration errors caused by locale mismatch between server and client. Server locale/User's browser settings "hu-HU"
maxDate Maximum date that the user can select. Periods partially overlapped by maxDate will also be selectable, although React-DateRange-Picker will ensure that no later date is selected. n/a Date: new Date()
maxDetail The most detailed calendar view that the user shall see. View defined here also becomes the one on which clicking an item in the calendar will select a date and pass it to onChange. Can be "month", "year", "decade" or "century". "month" "year"
minDate Minimum date that the user can select. Periods partially overlapped by minDate will also be selectable, although React-DateRange-Picker will ensure that no earlier date is selected. n/a Date: new Date()
monthAriaLabel aria-label for the month input. n/a "Month"
monthPlaceholder placeholder for the month input. "--" "mm"
name Input name prefix. Date from/Date to fields will be named "yourprefix_from" and "yourprefix_to" respectively. "daterange" "myCustomName"
nativeInputAriaLabel aria-label for the native date input. n/a "Date"
onCalendarClose Function called when the calendar closes. n/a () => alert('Calendar closed')
onCalendarOpen Function called when the calendar opens. n/a () => alert('Calendar opened')
onChange Function called when the user picks a valid date. If any of the fields were excluded using custom format, new Date(y, 0, 1, 0, 0, 0), where y is the current year, is going to serve as a "base". n/a (value) => alert('New date is: ', value)
onFocus Function called when the user focuses an input. n/a (event) => alert('Focused input: ', event.target.name)
onInvalidChange Function called when the user picks an invalid date. n/a () => alert('Invalid date')
openCalendarOnFocus Whether to open the calendar on input focus. Note: It's recommended to use shouldOpenCalendar function instead. true false
portalContainer Element to render the calendar in using portal. n/a document.getElementById('my-div')
rangeDivider Divider between date inputs. "–" " to "
required Whether date input should be required. false true
shouldCloseCalendar Function called before the calendar closes. reason can be "buttonClick", "escape", "outsideAction", or "select". If it returns false, the calendar will not close. n/a ({ reason }) => reason !== 'outsideAction'
shouldOpenCalendar Function called before the calendar opens. reason can be "buttonClick" or "focus". If it returns false, the calendar will not open. n/a ({ reason }) => reason !== 'focus'
showLeadingZeros Whether leading zeros should be rendered in date inputs. false true
value Input value. n/a
  • Date: new Date(2017, 0, 1)
  • String: "2017-01-01"
  • An array of dates: [new Date(2017, 0, 1), new Date(2017, 7, 1)]
  • An array of strings: ["2017-01-01", "2017-08-01"]
yearAriaLabel aria-label for the year input. n/a "Year"
yearPlaceholder aria-label for the year input. "----" "yyyy"

Calendar

DateRangePicker component passes all props to React-Calendar, with the exception of className (you can use calendarClassName for that instead). There are tons of customizations you can do! For more information, see Calendar component props.

License

The MIT License.

Author

Wojciech Maj Wojciech Maj

react-daterange-picker's People

Contributors

dependabot[bot] avatar jorrit avatar pmurphy-cs avatar victorandcode avatar wojtekmaj 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  avatar  avatar

react-daterange-picker's Issues

Provide divider text

So far this has proven to be a very nice package. One issue I have is the design we are working with requires us to have [start date] to [end date] where this package only uses "–". Im not familiar with overriding an npm package and thus asking here if its possible to get a prop of "divider" which can take a string or jsx element to be used in place of the default?

Thanks

Range divider not working

The rangeDivider attribute does not change anything when passing a string like " to " for example.

This is my package.json dependencies

"dependencies": { "@material-ui/core": "^4.9.0", "@material-ui/icons": "^4.9.0", "@material-ui/styles": "^4.9.0", "@wojtekmaj/react-daterange-picker": "^2.5.0", "axios": "^0.19.0", "material-table": "^1.50.0", "moment": "^2.24.0", "prop-types": "^15.7.2", "react": "^16.8.6", "react-dom": "^16.8.6", "react-google-login": "^5.0.4", "react-router-dom": "^5.0.0" },

Here is a demo with the error.

changing the date format

Hi @wojtekmaj ,
thanks for the package,
I have implemented the react-daterange-picker, but i want to get the value in format "dd-mm-yyyy",
but it was not working,
below is my code,


import React, { Component } from 'react';
import DateRangePicker from '@wojtekmaj/react-daterange-picker';

class MyApp extends Component {
  state = {
    date: [new Date(), new Date()],
  }

   render() {
console.log(this.state.date);
    return (
      <div>
        <DateRangePicker
          onChange={value => {
                      this.setState({ date: value });
                    }}
          value={this.state.date}
          format="dd-mm-yyyy"
        />
      </div>
    );
  }
}

shows in format [Tue Jan 07 2020 10:55:20 GMT+0800 (Philippine Standard Time), Tue Jan 07 2020 10:55:20 GMT+0800 (Philippine Standard Time)]

but Expected [07-01-2020, 07-01-2020]

Add style prop

It would be nice to add styles prop so that it is much easy to customize styles.

Is there a way to have an access to an array of all dates within the range?

Hi Wojtek,

Thank you for your great work!

I think it would be a good feature to have access to all dates within given range, not only to an array of a starting and ending date. What do you think about that?

Of course it is possible to calculate it basing only on those two dates but build in version would be more elegant and less time-consuming :)

Or maybe there is already a possibility to achieve what I'm thinking about, ie. I need to have a range of dates which will be send to backend and then to db in order to get it from another calendar (in different place in app) which will use it as disabled dates (using it as a range)?

Thanks again!

Problem with input fields size

I have proble with width of input text field. I see that in style component insert width with width of arrow spinners. I add this style

.react-date-picker__button__input__input::-webkit-outer-spin-button,
.react-date-picker__button__input__input::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

but it not help me.

typescript support¿

I'm looking for a library that handles date range selection for days, month and years but I'm currently using typescript. Any plan to include types definition here? I tried to generate one using dts-gen but couldn’t

Prop 'showDoubleView' not working

Hello,

is there a bug or maybe I using the react-date-rangepicker in a wrong way ?

The prop showDoubleView is taken from the react-calender and should show 2 month
in react-date-rangepicker, if I read this here correctly. But it seems it is not working.

<DateRangePicker
    showDoubleView
/>

Here ist a simple example @ https://codesandbox.io/s/thirsty-rubin-ldt4z

According documentation, i use the following packages:

    @wojtekmaj/react-daterange-picker": "2.5.0
    react-calendar": "^3.0.1

Thank you!

Doesn't open automatically on React Modal

Hi, thanks for such a lightweight library. I really love using this. One problem. When I use it outside of the any modal, it works as expected. But when I have it inside React Modal, and I have the isOpen defaults to true, but it still doesn't open the calendar automatically when the modal opens. Can you please tell me where I am going wrong?
Thanks in advance.

unexpected token

unexpected token .

1 | module.exports = require("@wojtekmaj/react-daterange-picker");
tafak?

when use '@wojtekmaj/react-daterange-picker/dist/entry.nostyle' its ok

CSS Not Loading

First off, AMAZING project! I love all of your work.

The only issue I seem to be having is with this component - it seems as if the CSS is not loading for some reason. The demo link in the readme also seems to be down, so I can't see what it's even supposed to look like. Any thoughts?

Daterange shows one month ahead in the picker

code:

this.state.date = [newDate(2020,1,5), new Date(2020,2,5)];

But in the DateRange picker on frontEnd it shows 2020/02/05 - 2020/03/05
Moves one month ahead for start date and end date.

Unselect / Clear date range

Is there a way to unselect / clear the date range natively in the component?

I've also tried to set the value back to null but the browser becomes unresponsive and yields no error.

CSS.supports is not a function in test

using react-testing library and jest throw an error TypeError: CSS.supports is not a function

temporary fix: adding global.CSS = { supports: jest.fn() };

the issue is related to react-fit package.

update: react-fit is used also in react-date-picker so i guess the same error should happen.

Error with next.js

I just installed and copied the example code from readme.md
image

And then get this error,
image

My project is on Next.js

getting date in string without timeZone

Hii, i m used used this package and working properly but i was required only date and time but Timezone is bot require, so can you give me datetime string feature without timezone?? i was send the screen shot, what exactly getting from output when i was using dateRange
Example: "Fri Dec 20 2019 00:00:00 GMT+0530 (India Standard Time)" ==> Getting this string
and what i was need from you
Example: "Fri Dec 20 2019 00:00:00 GMT+0530"
can you give me that type return value ??

NPM/Yarn install command incorrect

Hey, just an FYI that it looks like your NPM/Yarn install command is incorrect. The command you list:

yarn add react-daterange-picker

actually installs this package: https://github.com/onefinestay/react-daterange-picker (which is the one on the NPM registry: https://www.npmjs.com/package/react-daterange-picker).

I think you may need to register the package on NPM as a different name (perhaps scoped to your username?) or if it's already under a different name, it might be nice to update your README (I'm glad to submit a PR if you let me know the actual location!).

Just noticed this when trying to help someone out on StackOverflow who's trying to install your package.

Oh, also, it seems like the demo link is broken at the moment: http://projects.wojtekmaj.pl/react-daterange-picker/ returns a 404.

CSS classes on initial state

On the month view "button.react-calendar__tile" has class "react-calendar__tile--rangeStart" / "react-calendar__tile--rangeEnd" only when range is selected by user. On initial state start and end points has only the class "react-calendar__tile--active"

I've highlighted the start and end dates on my calendar and when I set user's previous selections on componentDidMount the above classes are missing and my calendar looks silly :)

Access to onOpen & onClose Events

Hey guy,

Thanks for the awesome projects, been using this and calendar on my app.

A little feedback: Currently clicking on leading zeroes won't cause the calendar to appear. This is also the case with clicking the slashes between dates. I won't make assumptions as to whether this is intended behaviour, but it's something I'd like to change in my implementation.

I've tried manually forcing the calendar open when a click occurs on the input group wrapper by setting an open state on the parent onClick, but I can't tell the parent when the picker has closed, so it only works one time.

Having access to onOpen and onClose events regardless of a value change would help us have greater control over the picker. Therefore I request this as a feature.

Thanks a lot, let me know if I'm overlooking something. Or if this is something you're happy with including in the project I can make a pull request.

Joe

Min/Max Date Issue

Min date issue.

I have simply added your package with non-other customization but the user can easily select any date.

class DateRangeInput extends Component {
  state = {
    date: [new Date(), new Date()]
  };

  onChange = date => this.setState({ date });

  render() {
    const { className, placeholder } = this.props;
    return (
      <div>
        <DateRangePicker onChange={this.onChange} value={this.state.date} />
      </div>
    );
  }
}

daterange picker

"Start date - End date" placeholder?

Hi, I'm wondering if it's possible for us to pass in our own text inputs to be used with this plugin? Taking a quick look through the source code, I didn't come across anything to do this, but I may be wrong?

I'm basically looking to use my own inputs, so I can show placeholders when no date is selected; something similar to Start Date - End Date. I can probably achieve this through adding my own styles and setting some flags in the onChange prop, but I'm wondering if there's a more straight forward out-of-the-box solution?

Thanks!

Problem with the import of the module

Hi,

I am trying to use the date range picker, but upon import, it displays the message of module not found:

./src/components/MyComponent.js Module not found: Can't resolve 'react-daterange-picker' in '/MyAppPath/components'

I have checked the node_modules directory and the 'react-daterange-picker' folder is there. And I have restarted node, re-installed everything but the error keeps appearing.

Am I missing something? Can anyone help me?

Thanks!

keep the calendar open after selection

Can I keep the calendar open, even after I selected the date range, but hide the wrapper footer element?
basically I only need the wrapper to be visible on screen and I need it to be persistent even after I finish my selection

Date Range Picker month dropdown turn off

In daterange picker, when I use format='MMM, dd yy' or format='MMM dd yy', there appears a dropdown of months alongside the calendar popup. Is there any way to turn off the month dropdown?

Build error "SyntaxErrorSyntaxError: src/DateRangePicker"

Hi Wojtek, thank you for your great date range component!

But i have an issue when try to build package manually. How can i fix it?

 yarn run build-js && yarn run copy-styles && yarn run build-styles
$ babel src -d dist --ignore __tests__
SyntaxError: src/DateRangePicker.jsx: Unexpected token (25:8)
  23 |   }
  24 | 
> 25 |   state = {};
     |         ^
  26 | 
  27 |   get eventProps() {
  28 |     return makeEventProps(this.props);
error Command failed with exit code 1.

How to select only startDate or endDate if one is already selected

Hi,

I´m trying to use the component as a filter startDate/endDate, when I´m having a "startDate" and don´t want to add endDate, I´m using null as a value for endDate, but If I want to add an endDate without resetting the startDate, I want to add just the new Date, not selecting startDate and endDate range all over again.

is it possible?

I think one way to do it is execute onChange function for startDate and also for endDate, not just for the range, I was checking on the react-calendar, this can be donde with allowPartialRange={true} prop, but we have no option to do it or access any props to the calendar in react-daterange-picker.

Instructions for import aren't working

import DateRangePicker from 'react-daterange-picker';

results in

modules-runtime.js?hash=d1eecd73d908a65f4ba4ee86caaafed0fd902ce9:241 Uncaught Error: Cannot find module 'react-daterange-picker'
    at makeMissingError (modules-runtime.js?hash=d1eecd73d908a65f4ba4ee86caaafed0fd902ce9:241)
    at require (modules-runtime.js?hash=d1eecd73d908a65f4ba4ee86caaafed0fd902ce9:251)
    at BasicRangePicker.js (BasicRangePicker.js:1)
    at fileEvaluate (modules-runtime.js?hash=d1eecd73d908a65f4ba4ee86caaafed0fd902ce9:353)
    at require (modules-runtime.js?hash=d1eecd73d908a65f4ba4ee86caaafed0fd902ce9:248)
    at TradeDetails.js (TradeDetails.js:1)
    at fileEvaluate (modules-runtime.js?hash=d1eecd73d908a65f4ba4ee86caaafed0fd902ce9:353)
    at require (modules-runtime.js?hash=d1eecd73d908a65f4ba4ee86caaafed0fd902ce9:248)
    at TradeCreateEditView.js (TradeCreateEditView.js:1)
    at fileEvaluate (modules-runtime.js?hash=d1eecd73d908a65f4ba4ee86caaafed0fd902ce9:353)

Not sure if README is up-to-date or if this is a bug. Would really love to start using this in our project. I'm willing to help if you need it. Thanks!

daterange-picker accepts invalid inputs

Using daterange picker in my react js application.
Using version: 2.4.0

Issues:

  • Input fields for date & month accepts any length values
  • Input field for year field have min:1000 and max: 275760

Screenshot 2019-08-20 at 11 53 13 AM

Error "Unable to resolve path" when trying to use the package

./src/components/organismes/AddItemForm/AddItemForm.js
Line 5: Unable to resolve path to module 'react-daterange-picker' import/no-unresolved

i installed both yarn and npm but getting this error..but package is showing in node_modules folder

i tried this on two projects, getting same error

enqueueCallback is not a function

Hello,

I am trying to use your component on a react project but I am facing the following problem when I try to select a date range:

Uncaught TypeError: this.updater.enqueueCallback is not a function

React dependencies are declared as follow:

"react": "^16.0.0",
"react-dom": "^16.0.0",

Thank you for your help

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.