Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
/>
like image 711
Gorakh Nath Avatar asked Sep 05 '17 10:09

Gorakh Nath


People also ask

How do I clear the Datepicker value in react?

Instead of selected , change it to value . Then set its value to empty string if you want to clear it.

How do I turn off previous date in react?

To disable the past and future dates, we have to use the isValidDate property of the react-datetime.


1 Answers

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 : ''} />
   }}
/>
                                                
like image 88
Frédéric Chauvière Avatar answered Sep 28 '22 03:09

Frédéric Chauvière