Git Product home page Git Product logo

react-date-range's Introduction

react-date-range

npm npm npm sponsors

A date library agnostic React component for choosing dates and date ranges. Uses date-fns for date operations.

Notice ⚠️

This project is currently unmaintained because the original maintainers are busy with other things. It should be pretty stable in it's current state but we won't be updating it in the foreseeable future. If you are willing to maintain it, please fork and open a pr adding your fork's link to this readme.

Why should you use react-date-range?

  • Stateless date operations
  • Highly configurable
  • Multiple range selection
  • Based on native js dates
  • Drag n Drop selection
  • Keyboard friendly

Live Demo : http://hypeserver.github.io/react-date-range

Getting Started

Installation

npm install --save react-date-range

This plugin expects react and date-fns as peerDependencies, It means that you need to install them in your project folder.

npm install --save react date-fns

Usage

You need to import skeleton and theme styles first.

import 'react-date-range/dist/styles.css'; // main style file
import 'react-date-range/dist/theme/default.css'; // theme css file

DatePicker

import { Calendar } from 'react-date-range';

class MyComponent extends Component {
  handleSelect(date){
    console.log(date); // native Date object
  }
  render(){
    return (
      <Calendar
        date={new Date()}
        onChange={this.handleSelect}
      />
    )
  }
}

DateRangePicker / DateRange

import { DateRangePicker } from 'react-date-range';

class MyComponent extends Component {
  handleSelect(ranges){
    console.log(ranges);
    // {
    //   selection: {
    //     startDate: [native Date Object],
    //     endDate: [native Date Object],
    //   }
    // }
  }
  render(){
    const selectionRange = {
      startDate: new Date(),
      endDate: new Date(),
      key: 'selection',
    }
    return (
      <DateRangePicker
        ranges={[selectionRange]}
        onChange={this.handleSelect}
      />
    )
  }
}

Options

Property type Default Value Description
locale Object enUS from locale you can view full list from here. Locales directly exported from date-fns/locales.
className String wrapper classname
months Number 1 rendered month count
showSelectionPreview Boolean true show preview on focused/hovered dates
showMonthAndYearPickers Boolean true show select tags for month and year on calendar top, if false it will just display the month and year
rangeColors String[] defines color for selection preview.
shownDate Date initial focus date
minDate Date defines minimum date. Disabled earlier dates
maxDate Date defines maximum date. Disabled later dates
direction String 'vertical' direction of calendar months. can be vertical or horizontal
disabledDates Date[] [] dates that are disabled
disabledDay Func predicate function that disable day fn(date: Date)
scroll Object { enabled: false } infinite scroll behaviour configuration. Check out Infinite Scroll section
showMonthArrow Boolean true show/hide month arrow button
navigatorRenderer Func renderer for focused date navigation area. fn(currentFocusedDate: Date, changeShownDate: func, props: object)
ranges *Object[] [] Defines ranges. array of range object
moveRangeOnFirstSelection(DateRange) Boolean false move range on startDate selection. Otherwise endDate will replace with startDate unless retainEndDateOnFirstSelection is set to true.
retainEndDateOnFirstSelection(DateRange) Boolean false Retain end date when the start date is changed, unless start date is later than end date. Ignored if moveRangeOnFirstSelection is set to true.
onChange(Calendar) Func callback function for date changes. fn(date: Date)
onChange(DateRange) Func callback function for range changes. fn(changes). changes contains changed ranges with new startDate/endDate properties.
color(Calendar) String #3d91ff defines color for selected date in Calendar
date(Calendar) Date date value for Calendar
showDateDisplay(DateRange) Boolean true show/hide selection display row. Uses dateDisplayFormat for formatter
onShownDateChange(DateRange,Calendar) Function Callback function that is called when the shown date changes
initialFocusedRange(DateRange) Object Initial value for focused range. See focusedRange for usage.
focusedRange(DateRange) Object It defines which range and step are focused. Common initial value is [0, 0]; first value is index of ranges, second one is which step on date range(startDate or endDate).
onRangeFocusChange(DateRange) Object Callback function for focus changes
preview(DateRange) Object displays a preview range and overwrite DateRange's default preview. Expected shape: { startDate: Date, endDate: Date, color: String }
showPreview(DateRange) bool true visibility of preview
editableDateInputs(Calendar) bool false whether dates can be edited in the Calendar's input fields
dragSelectionEnabled(Calendar) bool true whether dates can be selected via drag n drop
calendarFocus(Calendar) String 'forwards' Whether calendar focus month should be forward-driven or backwards-driven. can be 'forwards' or 'backwards'
preventSnapRefocus(Calendar) bool false prevents unneceessary refocus of shown range on selection
onPreviewChange(DateRange) Object Callback function for preview changes
dateDisplayFormat String MMM d, yyyy selected range preview formatter. Check out date-fns's format option
dayDisplayFormat String d selected range preview formatter. Check out date-fns's format option
weekdayDisplayFormat String E selected range preview formatter. Check out date-fns's format option
monthDisplayFormat String MMM yyyy selected range preview formatter. Check out date-fns's format option
weekStartsOn Number Whether the week start day that comes from the locale will be overriden. Default value comes from your locale, if no local is specified, note that default locale is enUS
startDatePlaceholder String Early Start Date Placeholder
endDatePlaceholder String Continuous End Date Placeholder
fixedHeight Boolean false Since some months require less than 6 lines to show, by setting this prop, you can force 6 lines for all months.
renderStaticRangeLabel(DefinedRange) Function Callback function to be triggered for the static range configurations that have hasCustomRendering: true on them. Instead of rendering staticRange.label, return value of this callback will be rendered.
staticRanges(DefinedRange, DateRangePicker) Array default preDefined ranges -
inputRanges(DefinedRange, DateRangePicker) Array default input ranges -
ariaLabels Object {} inserts aria-label to inner elements
dayContentRenderer Function null Function to customize the rendering of Calendar Day. given a date is supposed to return what to render.

*shape of range:

 {
   startDate: PropTypes.object,
   endDate: PropTypes.object,
   color: PropTypes.string,
   key: PropTypes.string,
   autoFocus: PropTypes.bool,
   disabled: PropTypes.bool,
   showDateDisplay: PropTypes.bool,
 }

**shape of ariaLabels:

 {
   // The key of dateInput should be same as key in range.
   dateInput: PropTypes.objectOf(
     PropTypes.shape({
       startDate: PropTypes.string,
       endDate: PropTypes.string
     })
   ),
   monthPicker: PropTypes.string,
   yearPicker: PropTypes.string,
   prevButton: PropTypes.string,
   nextButton: PropTypes.string,
 }

Infinite Scrolled Mode

To enable infinite scroll set scroll={{enabled: true}} basically. Infinite scroll feature is affected by direction(rendering direction for months) and months(for rendered months count) props directly. If you prefer, you can overwrite calendar sizes with calendarWidth/calendarHeight or each month's height/width with monthWidth/monthHeight/longMonthHeight at scroll prop.

  // shape of scroll prop
  scroll: {
    enabled: PropTypes.bool,
    monthHeight: PropTypes.number,
    longMonthHeight: PropTypes.number, // some months has 1 more row than others
    monthWidth: PropTypes.number, // just used when direction="horizontal"
    calendarWidth: PropTypes.number, // defaults monthWidth * months
    calendarHeight: PropTypes.number, // defaults monthHeight * months
  }),

Release workflow

  • Merge everything that needs to be in the release to master
  • Open a new release PR than:
    • bumps version to appropriate one <new_version>
    • Update CHANGELOG.md
  • Make sure the demo and important features are working as expected
  • After merging, tag the master commit with release/<new_version> and let Github Action handle publishing
  • = Profit 🙈

TODOs

  • Make mobile friendly (integrate tap and swipe actions)
  • Add tests
  • Improve documentation

react-date-range's People

Contributors

aommm avatar beeant avatar bonny1992 avatar burakcan avatar carlrosell avatar dependabot[bot] avatar greybutton avatar imranolas avatar jacobrask avatar jamwise avatar kamyar avatar kazazor avatar keremciu avatar khuongdv avatar lexispike avatar mattfurness avatar mimshwright avatar mkg0 avatar mortargrind avatar nikeeshi avatar onurkerimov avatar sadams avatar spyna avatar stijndeschuymer avatar strada avatar thijssteel avatar trabianmatt avatar wallwhite avatar ydagana avatar yoonseonwoong 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  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

react-date-range's Issues

Today indication?

Hi,

I needed to have some color indication on the today day cell,
I noticed that only the today day cell has a "undefined" className so I added some css selectors,
It works fine but.. I'm guessing that's a bug and it will not stay that way in future versions.

Is there any elegant way of custom theming only the current day cell than this one?
And thanks you all for a useful component.
Cheers :)

Highlight range on hover

Great repo first off! 😄
Just wondering if there is support for highlighting the range of dates from the selected startDate to before actually selecting endDate.

Example:
I select 16th as startDate
I hover over to 20th and there is a range 'light highlight' from 17th to 20th
I move over to 22nd and the range 'light highlight' extends to 22nd
I click on 22nd as endDate and the range gets the current implementation of 'dark highlight'

Release 1.0

I think the library itself is in an enough condition to release 1.0. But before doing so; we need to complete and organize the documentation. @strada @fatiherikli mayday :)

Please provide api option to change language

Hey,

It would be nice if you could provide an api option to change language.

Now I am hard coding it manually in Calendar.js, like this _moment.locale('zh-cn').

But this does no good for team development, if my project has new team members, they would also have to add a line like this.

Also, the format api doesn't seem to work for me.

import React, { Component } from 'react';
import { DateRange } from 'react-date-range';

class MyComponent extends Component {
    handleSelect(range){
        // intuitively, I think here would log out dates in the set format,
        console.log(range);
        // but turns out I still need to do something like this
        // to get the right format dates
        // or did I set the format in a wrong way in the props?? 
        let startDate = range.startDate.format('YYYY-MM-DD') 
        console.log(startDate);
    }

    render(){
        return (
            <div>
                <DateRange
                    onInit={this.handleSelect}
                    onChange={this.handleSelect}
                    format={ 'YYYY-MM-DD' }  // set format here
                />
            </div>
        )
    }
}

release 0.2.0

@mattfurness @Jador
the 0.2.0 milestone is done 🎊 , but needs to be tested(manually) before the release since there are a lot of new features bundled in.

We also need to update the readme.
thanks for your efforts 💯

about locale

How change to other language?
Moment.js has the locale method, but how to change language in react-date-range?

update Locale weeddaysMin use only 1 character

I have a design like this

image

When use moment update locale. Everything working well. But the weekdaysMin you use as the React key, so i got the duplicate key problem S (Sunday) - S (Saturday), T (Tuesday) - T (Thursday).

moment.updateLocale('en', {
      months: [
        'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
        'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
      ],
      weekdaysMin: ['S', 'M', 'T', 'W', 'T', 'F', 'S']
    });

Could you replace the key with loop index. I think it's better.

Line 130 - 131 of Calendar.js

    for (let i = dow; i < 7 + dow; i++) {
      const day = moment.weekdaysMin(i);

      weekdays.push(
        <span style={onlyClasses ? undefined : styles['Weekday']} className={classes.weekDay} key={day}>{day}</span>
      );
    }

Thanks and best regards!

How To Customize defaultRange?

I wonder if I want to customize default range, I want to add last 60 days or something like that.
How to do that?

Thank you...

Allow theming and disabling of future dates

Hey,

is the separate theming and disabling of selection of the days after today possible?
I.e. I need to deny choosing of day after today and I want to make it look disabled.

Calendar width issues in Firefox.

I'm testing in Firefox on Xubuntu, and it looks like the calendar width is just a touch too small to render all seven days in a row.

Screenshot of problem:

Calendar width issue

Set no predefined value in calendar

Is there any chance to define no default value when displaying calendar? I want to use this plugin only for selecting ranges, but I want to display only blank calendars by default after first render.

Read Only

Hello,

is it possible to set DateRange as readOnly mode ?

thank

Responsive calendar

Is there a simple way in the theme object to make this calendar easily responsive?

Can't seem to use to select last 48h, last 72h, etc.

I know it probably makes little sense since a date picker is for picking, ahem, dates and not date-times. However, I'm already using react-date-range and I've been asked to provide some predefined links that (instead of just selecting "Today" or "Yesterday"), allow for easy selection of "Last 24h", "Last 48h" and the like.

As far as I could see, the use of startOf('day') across the codebase prevents such time spans from being selected with the component as it currently stands.

Have you got any ideas as to how I could add that functionality without tampering with the widget?

Would you consider adding the ability to select non-start-of-the-day timestamps with a flag (something like an allowNonFullDays prop) if I decided to implement it?

"Center" calendar view

Hi there,

Thanks for this great component! Installed it yesterday, and fit right in.

One thing I noticed was that when selecting a date range via the presets, the calendars might become out of sync. That is, the start date might actually be out of bounds of the left calendar. Is there a way to make sure both the start and end dates are always visible?

Thanks,

Alexis

Add time selector

Would be nice if the widget would also have selectors for hours and minutes.

Document Min & Max Props

I noticed as part of v2.0, min and max props were added but the documentation wasn't updated to show this.

Just thought I'd put a note in as it may be useful to a lot of people and with the documentation not containing these changes, it may have went unnoticed.

Changelog

The current version on NPM is 0.9.0, yet the latest tagged release is 0.2.4.

A user shouldn't have to sift through commits to figure out what changed. Especially when the module in question jumps up 7 minor versions.

Could you please consider maintaining a changelog?

GPL licensing

Is it really necessary to use GPL as a license? Right now every application that uses this component would need to be open sourced. As much as I love open source, this isn't always possible.

How about switching to the MIT license?

Range not updated when properties change

When I include and afterwards change x or y in the parent component, DateRange is not updated.

This is because DateRange doesn't use the props directly, but parses them and puts them into state, and this is only done in the constructor, and then never again.

Update min and max calendars for date range

Let's say I have the "Range Picker (Predefined Ranges)" example on the Examples page. Instead of Last 30 days, I define a range called "Last 6 Months". When I use it, the right calendar goes to today's date and the left calendar gets completely highlighted since it is within the last 6 months range.

This doesn't actually show the user what start date was selected since it isn't on the left calendar. It's several months before it.

When updating either calendar, it should automatically go to the month and year that was selected. There is no way to link a calendar to initially showing its selected day/date.


Another possible example of this is a predefined range for a set of specific dates in the past or future. For example I could have a predefined range called "Summer (2015)" which has a start date of July 1, 2015 and an end date of August 30, 2015. The date range picker should allow for some way to show those two dates highlighted in both of the calendars shown in my date range control.


Image:
ss 2016-03-22 at 02 19 49

This is how it looks when your start date is not on the two displayed calendars. The current calendars do not automatically move to their selected date when that date is first selected.

Addition of apply and cancel links

Thinking in terms of an enhancement. It would make sense as the onChange event fires on change of any value but when picking a range, having an apply event seems more suitable.

BUG with inline styles

I use DateRange component for my Date Range Picker and i try to specify style for day in range using DayInRange property in thema, and styles are applied. But after hovering mouse to this days styles become default value.
I will add code snapshot on Monday.

Passing dates in from state causes onChange twice

So, maybe this isn't the right way to do this so if it isn't, please correct me.

import * as React from "react";
import { render } from "react-dom";
import { DateRange } from "react-date-range";

interface IMyComponentState {
  startDate: Date;
  endDate: Date;
} 

class MyComponent extends React.Component<{}, {}> {
  state: IMyComponentState;

  constructor() {
    super();

    this.state = {
      startDate: new Date(),
      endDate: new Date(),
    };

    this.handleChange = this.handleChange.bind(this);
  }
  handleChange(dates) {
    console.log(dates);

    this.setState({
      startDate: dates.startDate,
      endDate: dates.endDate, 
    });
  }
  render() {
    return (
      <div>
        <DateRange
          startDate={this.state.startDate}
          endDate={this.state.endDate}
          onChange={this.handleChange}
        />
      </div>
    );
  }
}

render(<MyComponent />, document.getElementById("app"));

I figured I could pass in dates from my state. However, when I do this, clicking on dates causes the onChange to fire twice.

I figure it's because I noticed that the onChange fires both from an onClick AND from a willReceiveProps.

Has anyone ran into this before? I'm trying to figure out how else to maintain the currently selected dates in state so that when I close and open the calendar in my UI, it'll maintain the selected dates.

Thanks!

Tag releases

Please tag releases, which makes it easier to see what has changed between the versions that have been published at npm

onlyClasses is not defined

when i use the DateRange component with the property range , the browser show the error 'Uncaught ReferenceError: onlyClasses is not defined' .

image

i find the code in PredefinedRanges.js , line 57-83 . when i add the variate onlyClasses which is read from this.props , the component render successfully. thanks!

Uncaught ReferenceError: onlyClasses is not defined (0.2.3)

Hi there. I upgraded from 0.2.2 to 0.2.3 and I'm getting the following error:

Uncaught ReferenceError: onlyClasses is not defined

Uncaught ReferenceError: onlyClasses is not defined(anonymous function) @ PredefinedRanges.js?
23ea:77renderRangeList @ PredefinedRanges.js?23ea:66render @ PredefinedRanges.js?
...

Any ideas?

Inclusive End Date w.r.t Time

For the end date, date picker now gets the datetime as "YY/MM/DD 00:00:00" and I was thinking this might be better if it was "YY/MM/DD 23:59:59" so we include the entire last day with respect to time too. In use cases where time also matters along with the date (which is something I'm working on), this could be very useful. Also, we could probably also have a property inclusive? That would include or exclude start and end dates.
I will work on this and submit a pull request soon, unless people think this would not be of any use.

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.