reactjsreact-datetime

How to clear the value entered in react-datetime?


I am using react-datetime for our calendar control.Now the issue is that if the user entered an invalid date like 'djfdjfhjkhdf' then in this control nothing is there to validate.So I decided to write my own validation function and call that on blur event if the date is invalid then clear the text entered by the user.My code is like this:-

import DatePicker from 'react-datetime';

focousOut(value) {
if (!validateDate(value)) {
  this.setState({ startDate:  ''});
  this.setState({ selectedValue: '' });
 }
}
handleChange(date) {
 this.setState({ selectedValue: date });
 this.setState({ startDate: date });
}

<Datetime
  timeFormat={false}
  value={this.state.selectedValue}
  defaultValue={this.state.startDate}
  onChange={this.handleChange}
  onBlur={this.focousOut}
  locale='en-US'
  dateFormat
  closeOnSelect
/>

Solution

  • One of the issues seem to be that, based on the given props, you are creating a mix of a controlled and uncontrolled Datetime component. Basically, use value if you want a state-controlled component, or defaultValue to let the DOM manage the input value.

    See this part of the documentation:

    value - Represents the selected date by the component, in order to use it as a controlled component. This prop is parsed by Moment.js, so it is possible to use a date string or a moment object.

    defaultValue - Represents the selected date for the component to use it as a uncontrolled component. This prop is parsed by Moment.js, so it is possible to use a date string or a moment object.


    Have a look at this forked codepen I made.

    var date = new Date();
    
    class App extends React.Component {
      constructor() {
        super();
        this.state = {selectedValue: ''};
        this.focousOut = this.focousOut.bind(this);
        this.handleChange = this.handleChange.bind(this);
      }
      
      focousOut(value) {
        if(!moment(value).isValid()) {
         this.setState({selectedValue: ''}); 
        }
      }
      
      handleChange(date) {
       this.setState({ selectedValue: date });
      }
    
      render() {
        return (
           <Datetime
             timeFormat={false}
             value={this.state.selectedValue}
             onChange={this.handleChange}
             onBlur={this.focousOut}
             locale='en-US'
             dateFormat
             closeOnSelect
           />
        );
      }
    }
    
    React.render(<App />, document.body);
    

    Also, you can use the moment.js library to easily determine if a string is of a valid Date format. Just use moment().isValid().

    I should note that the onBlur event seems to trigger on the 2nd blur. Not sure why that is, but perhaps the you'll find an answer in the docs. The above is only a fix to your existing code, and hopefully a useful guideline to get you started.