Search code examples
javascriptreactjsreact-dates

How can I get DateRangePicker to render calendars on click?


When I render this in webpack-dev-server, the calendar doesn't render on click.

enter image description here

If I try to change the date manually, I get an error:

DateSelection.js?f52c:25 Uncaught TypeError: Cannot read property 'calendarFocus' of null

SingleDatePicker seems to work just fine, but not DateRangePicker. What can I do to render the calendar correctly on click?

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import moment from 'moment';
import { DateRangePicker } from 'react-dates';
import 'react-dates/initialize';
import 'react-dates/lib/css/_datepicker.css';

class DateSelection extends Component {
  constructor(props) {
    super(props);
    this.state = {
      startDate: moment(),
      endDate: moment(),
      calendarFocus: 'startDate',
    }
    this.onDatesChange = this.onDatesChange.bind(this);
    this.onFocusChange = this.onFocusChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  };

  onDatesChange({ startDate, endDate }) {
    this.setState(() => ({ startDate, endDate }));
  };

  onFocusChange({ calendarFocus }) {
    this.setState(() => ({ calendarFocus }));
  };

  onSubmit(e) {
    e.preventDefault();
    console.log(this.state);
  };

  render() {
    return (
      <form onSubmit={this.onSubmit}>
        <DateRangePicker
          startDate={this.state.startDate}
          startDateId="startDate"
          endDate={this.state.endDate}
          endDateId="endDate"
          onDatesChange={this.onDatesChange}
          focusedInput={this.state.calendarFocus}
          onFocusChange={this.onFocusChange}
        />
        <br/>
        <input type="submit" value="Submit" />
      </form>
    );
  }
};

ReactDOM.render((
  <DateSelection/>
), document.getElementById('root'));

Other details:

  • react 16.2.0
  • react-dates 16.3.5
  • webpack 3.10.0
  • webpack-dev-server 2.11.1

Also, as an aside, I can't seem to find the current docs of react-dates. A lot of places link me to this storybook, but it seems some information is missing. For example, the Description column here is blank.

enter image description here


Solution

  • Try setting calendarFocus to null in the constructor.

    And Change

    onFocusChange({ calendarFocus }) {
      this.setState(() => ({ calendarFocus }));
    };
    

    to

    onFocusChange(calendarFocus) {
      this.setState(() => ({ calendarFocus }));
    };