How to clear the value entered in react-datetime?

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.


Yeah, there's clearly a rendering bug in component if you try to pass a null or empty value in controlled component mode: the internal input still got the former value entered with the calendar (uncontrolled ?) despite the fact that that.state.value is null : I've been able to "patch" it with the renderInput prop :

<Datetime
   value={(this.state.date) ? this.state.date : ''} 
   onChange={(value) => { this.setState{(date : ((value) && (isNaN(new Date(value)) === false)) ? new Date(value)).format('yyyy-mm-dd')  null, attribute) }} 
   renderInput={(props) => {
       return <input {...props} value={(this.state.date) ? props.value : ''} />
   }}
/>