GithubHelp home page GithubHelp logo

hacker0x01 / react-datepicker Goto Github PK

View Code? Open in Web Editor NEW
7.8K 84.0 2.2K 104.91 MB

A simple and reusable datepicker component for React

Home Page: https://reactdatepicker.com/

License: MIT License

CSS 0.07% JavaScript 96.64% Shell 0.05% HTML 0.12% SCSS 3.12%
datepicker-component react javascript moment picker date-fns hacktoberfest

react-datepicker's Introduction

React Date Picker

npm version Test suite codecov Downloads

A simple and reusable Datepicker component for React (Demo)

Installation

The package can be installed via npm:

npm install react-datepicker --save

Or via yarn:

yarn add react-datepicker

You’ll need to install React and PropTypes separately since those dependencies aren’t included in the package. If you need to use a locale other than the default en-US, you'll also need to import that into your project from date-fns (see Localization section below). Below is a simple example of how to use the Datepicker in a React view. You will also need to require the CSS file from this package (or provide your own). The example below shows how to include the CSS from this package if your build system supports requiring CSS files (Webpack is one that does).

import React, { useState } from "react";
import DatePicker from "react-datepicker";

import "react-datepicker/dist/react-datepicker.css";

// CSS Modules, react-datepicker-cssmodules.css
// import 'react-datepicker/dist/react-datepicker-cssmodules.css';

const Example = () => {
  const [startDate, setStartDate] = useState(new Date());
  return (
    <DatePicker selected={startDate} onChange={(date) => setStartDate(date)} />
  );
};

Configuration

The most basic use of the DatePicker can be described with:

<DatePicker selected={startdate} onChange={(date) => setStartDate(date)} />

You can use onSelect event handler which fires each time some calendar date has been selected

<DatePicker
  selected={date}
  onSelect={handleDateSelect} //when day is clicked
  onChange={handleDateChange} //only when value has changed
/>

onClickOutside handler may be useful to close datepicker in inline mode

See here for a full list of props that may be passed to the component. Examples are given on the main website.

Time picker

You can also include a time picker by adding the showTimeSelect prop

<DatePicker
  selected={date}
  onChange={handleDateChange}
  showTimeSelect
  dateFormat="Pp"
/>

Times will be displayed at 30-minute intervals by default (default configurable via timeIntervals prop)

More examples of how to use the time picker are given on the main website

Localization

The date picker relies on date-fns internationalization to localize its display components. By default, the date picker will use the locale globally set, which is English. Provided are 3 helper methods to set the locale:

  • registerLocale (string, object): loads an imported locale object from date-fns
  • setDefaultLocale (string): sets a registered locale as the default for all datepicker instances
  • getDefaultLocale: returns a string showing the currently set default locale
import { registerLocale, setDefaultLocale } from  "react-datepicker";
import { es } from 'date-fns/locale/es';
registerLocale('es', es)

<DatePicker
  locale="es"
/>

Locales can be changed in the following way:

  • Globally - setDefaultLocale('es');

Compatibility

React

We're always trying to stay compatible with the latest version of React. We can't support all older versions of React.

Latest compatible versions:

  • React 16 or newer: React-datepicker v2.9.4 and newer
  • React 15.5: React-datepicker v2.9.3
  • React 15.4.1: needs React-datepicker v0.40.0, newer won't work (due to react-onclickoutside dependencies)
  • React 0.14 or newer: All above React-datepicker v0.13.0
  • React 0.13: React-datepicker v0.13.0
  • pre React 0.13: React-datepicker v0.6.2

Moment.js

Up until version 1.8.0, this package was using Moment.js. Starting v2.0.0, we switched to using date-fns, which uses native Date objects, to reduce the size of the package. If you're switching from 1.8.0 to 2.0.0 or higher, please see the updated example above of check out the examples site for up to date examples.

Browser Support

The date picker is compatible with the latest versions of Chrome, Firefox, and IE10+.

Unfortunately, it is difficult to support legacy browsers while maintaining our ability to develop new features in the future. For IE9 support, it is known that the classlist polyfill is needed, but this may change or break at any point in the future.

Local Development

The main branch contains the latest version of the Datepicker component.

To begin local development:

  1. Run yarn link from project root
  2. Run cd docs-site && yarn link react-datepicker
  3. Run yarn install from project root
  4. Run yarn build from project root
  5. Run yarn start from project root

The last step starts documentation app as a simple webserver on http://localhost:3000.

You can run yarn test to execute the test suite and linters. To help you develop the component we’ve set up some tests that cover the basic functionality (can be found in /tests). Even though we’re big fans of testing, this only covers a small piece of the component. We highly recommend you add tests when you’re adding new functionality.

Please refer to CONTRIBUTING.md file for more details about getting set up.

The examples

The examples are hosted within the docs folder and are ran in the simple app that loads the Datepicker. To extend the examples with a new example, you can simply duplicate one of the existing examples and change the unique properties of your example.

Accessibility

Keyboard support

  • Left: Move to the previous day.
  • Right: Move to the next day.
  • Up: Move to the previous week.
  • Down: Move to the next week.
  • PgUp: Move to the previous month.
  • Shift+PgUp: Move to the same day and month of the previous year. If that day does not exist, moves focus to the last day of the month.
  • PgDn: Move to the next month.
  • Shift+PgDn: Move to the same day and month of the next year. If that day does not exist, moves focus to the last day of the month.
  • Home: Move to the first day (e.g Sunday) of the current week.
  • End: Move to the last day (e.g. Saturday) of the current week.
  • Enter/Esc/Tab: close the calendar. (Enter & Esc calls preventDefault)

For month picker

  • Left: Move to the previous month.
  • Right: Move to the next month.
  • Enter: Select date and close the calendar

License

Copyright (c) 2014-2023 HackerOne Inc. and individual contributors. Licensed under MIT license, see LICENSE for the full license.

react-datepicker's People

Contributors

abdubek avatar aij avatar czabaj avatar dependabot[bot] avatar earthslasthope avatar franmc01 avatar gautam-pahuja avatar hahahana avatar imartzen avatar jochenberger avatar kevinfabre-ods avatar kmdtqm avatar lbekkema avatar lemming avatar liamhubers avatar martijnrusschen avatar mgrdevport avatar mxschmitt avatar ntdb avatar rafeememon avatar rohanvachheta avatar rso avatar sauter001 avatar scottagirs avatar shreekeshmurkar avatar tanmayintelli avatar tc-ww avatar xmakina avatar yuki0410-dev avatar zarthus 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  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

react-datepicker's Issues

Support for up- and down keys in the input

When the cursor is placed near the year and the user presses the up-key, it would be nice to see the year get incremented. Same goes for month and day.

This is not a launch blocker or whatever, just a nice-to-have.

ReferenceError: document is not defined

When I try to server render using Node.js + Express + ReactRouter, I get this:

C:\Projects\Git\gearz\node_modules\react-datepicker\node_modules\tether\dist\js\tether.js:406
var el = document.createElement('div');
         ^
ReferenceError: document is not defined

You are assuming document exists, which isn't true when you are server rendering.

The most curious part is that I'm copying my example from the server rendering example. This is how my component looks like:

    var Example = React.createClass({
        getInitialState: function () {
            return {date: moment()};
        },
        onChange: function () {},
        render: function () {
            return React.createElement(
                DatePicker,
                {
                    selected: this.state.date,
                    onChange: this.handleChange
                }
            );
        }
    });

Am I doing anything wrong?

Improve examples

The current examples don't cover all features of the datepicker. We should make sure all features are covered in the examples.

We can use Github pages to create a nice example page. I imagine something that shows the code example on the left and the actual output on the right for each feature/example.

Optionally, we could use React Playgrounds to give people the ability to play with the code within the example page.

Datepicker demo not working on Github

The demo (mentioned in the readme) isn't working anymore since the latest PR's has been merged. We should update the dependencies to be fetched from external domains.

Unable to set selected state from external component

I think there is an issue with the selected state value. Specifically, a parent component can set the selected value by passing it as a prop, but if the parent were to change its value, the DatePicker component does not receive the update. I have a separate "Clear" button on my page that should be able to clear the input. I believe the root of the issue is the use of getInitialState() to set selected value from the prop:

getInitialState: function() {
    return {
      focus: false,
      selected: this.props.selected
    };
  },

The documentation states this as an antipattern: https://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html

I believe the solution is to have a componentWillReceiveProps that can keep the selected state updated on changes, something like:

componentWillReceiveProps(newProps){
  this.setState({
    selected: newProps.selected
  });
}

What do you think? I'm happy to submit a pull request.

Problem with className property of DateInput component

It used to be possible to pass in a className property to style the DateInput component, but recent changes have caused the className to automatically be assigned to "datepicker__input" instead of this.props.className.

Dependency on React < 0.13

Is it necessary to limit React to < 0.13 in bower.json?
If not, a new release with that limit removed would be much appreciated! 😄
(I can submit a PR with that change if needed)

Show the arrow on the correct side of the datepicker

Right now, we always show the arrow on the top-left corner of the date-picker. However, when there isn't enough space below the input, the date-picker is shown above the input. When this happens, the arrow should be shown on the correct side.

Tether has helper-classes for this.

npm package has jsx files in src with js extension

hi,

while trying to use react-datepicker:0.5.1 I'm getting following:

ERROR in ./~/react-datepicker/src/datepicker.js
Module parse failed: ...\node_modules\react-datepicker\src\datepicker.js Line 50: Unexpected token <
You may need an appropriate loader to handle this file type.
|     if (this.state.focus) {
|       return (
|         <Popover>
|           <Calendar
|             selected={this.props.selected}
 @ .../some_file.cjsx 13:13-40

this is produced by webpack. naturally my webpack config only applies jsx-loader to files with appropriate extension (*.jsx). can you please keep extension at .jsx for files in /src when you dist the npm package?

incompatible with React version below 0.13.0

attempting to load, I get the following error:

Uncaught TypeError: React.findDOMNode is not a function

The findDOMNode API was introduced in React 0.13, which is the root cause of the problem. I'd be happy to put in a fix, although perhaps the library is meant not to support older versions of React. interested to hear your thoughts.

Improve test coverage

The current test coverage does only cover some basic features. To keep a stable datepicker we should expand the test coverage and keep track of the current coverage by making sure each new feature has enough coverage.

Cannot read property 'classSet' of undefined

Might be worth noting somewhere that this package requires react with addons for the classSet utility to work correctly. And with that being depreciated soon, maybe looking at including another utility.

For the time being, I was able to get it working in my app with var React = require('react/addons');

Support configuring the className of the <input> element

Thank you for this great component!

For those using a CSS library (eg. Bootstrap) there is usually a specific class that we need to add to all <input> elements, such as form-control, for them to follow the library style.

Right now we can replace datepicker__input with form-control in the datepicker JS file (what I'm doing) or copy all the Bootstrap CSS with the datepicker class name.

It would be cool to have className on the Datepicker passed to the input element.

Error when running npm install

npm ERR! Darwin 14.1.0
npm ERR! argv "node" "/usr/local/bin/npm" "install"
npm ERR! node v0.12.1
npm ERR! npm  v2.7.3
npm ERR! code EPEERINVALID

npm ERR! peerinvalid The package jest-cli does not satisfy its siblings' peerDependencies requirements!
npm ERR! peerinvalid Peer [email protected] wants jest-cli@^0.1.17

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/martijn/Development/react-datepicker/npm-debug.log

If minDate and maxDate have values the selected date should be between them

To create between and not between functionality the calendar should respect the following rules:

  • If minDate < maxDate the selectedDate must be between minDate and maxDate.
  • If maxDate < minDate (which sounds strange, but hear me out), the selectedDate must be before maxDate and after minDate. (e.g. not between maxDate and minDate).

Support for React 0.13

I'm using React 0.13 and this causes react-datepicker to show a warning about getDOMNode being deprecated. (https://facebook.github.io/react/blog/2015/03/10/react-v0.13.html#new-features).

For lines like this in the code:

this.refs.input.getDOMNode().focus();

... what would your thoughts be about abstracting out getDOMNode and putting it behind a utility function that could be swap between getDOMNode and findDOMNode? The utility function would always return a node, so the client code would never know how it got the node, only that it got one.

In the build process you could specify the React version you want and the utility function would be wired to only include the support method for the appropriate version of React.

Something like (pseudo code):

if (__REACT_VERSION_0.12__) {
  return getDOMNode(component);
} 

if (__REACT_VERSION_0.13__) {
  return findDOMNode(component);
}

That's the current approach I use with webpack and environment variables to build different versions of components.

Or maybe just live with the warnings in dev. =)

ref error

[Error] TypeError: null is not an object (evaluating 's.findDOMNode(this.refs.input).blur')

[Error] Error: Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. This usually means that you're trying to add a ref to a component that doesn't have an owner (that is, was not created inside of another component's render method). Try rendering this component inside of a new top-level component which will hold the ref.

Support dynamic props

There's no way to set other props on the datepicker input element - it's a black box.

So if I wanted to add props such as onBlur, aria-*, className or anything else that is not explicitly added, they are simply ignored.

Update dist files

Hi,
I noticed that the files in /dist folder are not up to date, SSR rendering doesn't work for example. Could you please build those and update to npm?

Thanks!

Moment.js as a peer dependency

Hi,

Moment.js is a big dependency that I don't want to add twice to my bundle. Could it be moved to the peerDependencies in package.json like react?.

Thanks for this component, works great.

Cheers,
Javi

Clicking on a day causes the datepicker to close without selecting

Steps to reproduce:

  1. Go to http://localhost:8000
  2. Open the datepicker (focus the input area)
  3. Hard click on a date (no tap, if you're on a Macbook)

Expected:
The datepicker should be closed and the selected date should be filled in the input area

Received:
The datepicker is closed, but the new date is not selected

Tested browsers:

  • Firefox 30.0
  • Chrome 35.0.1916.153

Hardware:
Macbook Air

What's super strange:
Tapping actually works to select the date, clicking does not.

Move lodash to dependencies

Error in webpack:

ERROR in ./~/react-datepicker/dist/react-datepicker.min.js
Module not found: Error: Cannot resolve module 'lodash' in /app/node_modules/react-datepicker/dist
 @ ./~/react-datepicker/dist/react-datepicker.min.js 1:117-134

Invalid changes to the input box are not reverted when the calendar is hidden

If you try this:

  1. Click on the text box, this should bring up the calendar
  2. Clic again inside it, this will hide the calendar
  3. Type some nonsense in the textbox
  4. Click outside

This will leave the textbox with garbage inside it, while the state still contains the last valid date.

Correct behaviour would be either reverting the garbage, or disabling hiding the calendar altogether while the text box is focused (by adding className ignore-react-onclickoutside to the input element)

Disabled prop not working correctly

It seems that the disabled property is not working as it was when I submitted my pull request. The input should have the disabled HTML property and not allow the input to have focus. This is no longer the case.

Unable to run with npm/browserify

Out of the box this is not working if I just import the package using requireJS/browserify. The external dependencies (React, moment, Tether) are assumed to be globals in the source. @RSO are you aware of this issue? I notice there is another issue #42 but not sure how thoroughly tested that was.

Add ability to disable days in the future or past

The datepicker ables users to select dates in the future or past, but for some cases these dates are not applicable. For example if you'd have a dashboard, you want to force users to only select dates in the past. Or if you'd have an appointment scheduler you want to force users to select dates in the future.

disabled props

Hello. Thanks for this nice component. But there was a need to disable INPUT under certain conditions.
It would be great if the components looks like:

Thanks!

Uncaught TypeError: this.props.onChange is not a function

Hi,
i use the datepicker like this.

if i click on the datepicker input field the calender opens, but when i click on a date...i get the error message Uncaught TypeError: this.props.onChange is not a function

had someone a problem like this and can help me please´?

br

calendar displays wrong days with minDate

I have a DatePicker that looks like this:

<DatePicker
        key="somekey"
        selected={moment()}
        onChange={this.setDeterminationDate}
        minDate={moment().subtract(10, 'days')}
        maxDate={moment().add(10, 'days')}
        placeholderText="Determination Date" />

this causes the calendar to display the wrong dates like this

Friday is the 5th not Saturday.

Do you consider a new release

Thank you for this, it is the best datepicker so far i found.

I installed v0.6.0 through npm and popover was not working fine. Problem was calendar popped on top of inputs if it is 6 line long. I realize problem is about tether options on popover.jsx, while i was trying to fix found out that you also changed tether options but did not release. So i forked and used own release it works much better now.

TL;DR: popover position problem is fixed in source but not is latest release.

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.