Colfah
Colfah

Reputation: 358

React Datepicker - wrong date showing when I bind to enable e.preventDefault()

Datepicker is detecting the correct date but the form is refreshing.

So, I inserted e.preventDefault() into the function.

This gave me an error saying e.preventDefault() is not a function.

So I changed the function to use bind

onChange={(event)=> this.changeStartDetails.bind(this)}

But now, no matter what date I select, datePicker registers it as today at midnight.

Where am I going wrong?

The full code is here

Summary code is below:

  constructor(){
        super()
        this.changeStartDetails= this.changeStartDetails.bind(this)
        } 

changeStartDetails(e){

   e.preventDefault()

    console.log('e', e)
    console.log('moment(e)', moment(e).format('DD MM YY HH:mm'))
    console.log('moment()', moment().format('DD MM YY HH:mm'));
    console.log('!moment(e).isAfter(moment())', !moment(e).isAfter(moment()));
}

   <form>

            <DatePicker
                className="datePicker"
                timeIntervals={15}
                selected={this.state.startDetails}
                onChange={(event)=> this.changeStartDetails.bind(this)}
                showTimeSelect
                dateFormat="d MMM yyyy HH:mm"
                required
                placeholderText={'Date & Time Event Starts'}
            />

    </form>

Upvotes: 1

Views: 1386

Answers (1)

ezio4df
ezio4df

Reputation: 4105

Your mistaken here,

onChange={(event)=> this.changeStartDetails.bind(this)}

Your mistakenly binding your event listener in AND also calling in callback function.

You probably meant something like this,

onChange={this.changeStartDetails.bind(this)}

Or,

onChange={event => this.changeStartDetails(event)}

EDIT: in this test everything worked, there wasn't any form refreshing also.

function App() {
    const [sdate, setSDate] = useState(new Date());
    return (
        <div className="App">
            <DatePicker
                className="datePicker"
                timeIntervals={15}
                selected={sdate}
                onChange={(event) => {
                    console.log('onChange', event);
                    setSDate(event);
                }}
                showTimeSelect
                dateFormat="d MMM yyyy HH:mm"
                required
                placeholderText={'Date & Time Event Starts'}
            />
        </div>
    );
}

Upvotes: 2

Related Questions