Search code examples
javascriptreactjsreact-datepicker

If there is no value display default date - date-picker - ReactJs


I am finding my way out with the react-datepicker , and everything runs smoothly until i delete the input date filed it throws me an error : index.js:372 Uncaught RangeError: Invalid time value . I get it proabally the error comes from there because there is no a default date in use . So my question is how can i fix that . Here is an example of my code :

this.state= {
            startDate: moment().startOf('day').subtract(20, 'days'),
            endDate: moment().startOf('day').add(1,'days'),
}

   handleStartDate = date => {

        this.setState({
            startDate: moment(date).startOf('day')
        }, () => {
            if (moment(date).startOf('day').isAfter(this.state.endDate)) {
                this.setState({
                    endDate: moment(date).startOf('day').add(1,'days')
                })
            }
        });
    }

    handleEndDate = date => {
        this.setState({
            endDate: moment(date).startOf('day').add(1,'days')
        });
    };

...
 return (
      <DatePicker
          id='startDate'
          dateFormat="dd/MM/yyyy"
          defaultValue = {this.startDate}
          selected={this.state.startDate.toDate()}
          onChange={this.handleStartDate}
       />

      <DatePicker
          id='endDate'
          dateFormat="dd/MM/yyyy"
          minDate={this.state.startDate.toDate()}
          selected={this.state.endDate.toDate()}
          onChange={this.handleEndDate}
       />

)


Solution

  • Its not actually a default value issue, you just need to check if that passed argument from onChange method is holding some values.

    handleStartDate = date => {
      // When you delete the input value "date" will return null
      // So if no values, just do nothing
      if (!date) return
    
      //...
    
    }
    

    And same goes for handleEndDate

    Edit react-datepicker-start-end-example


    Also, if you are trying to do some Date Picker Range I guess you might find @y0c/react-datepicker more useful. Here is an codeSandbox example