James Delaney
James Delaney

Reputation: 1776

Datepicker onChange issue React

On datepicker I have an onChange event. The problem is when a user starts to manually change date.

if user only changes day, the onChange function is called and will send req for data.

And if user continue to make changes manually, every time onChange is executed, which causes performance issue.

How can I avoid this problem?

Sample of Datepicker code:

 <Form.Field>
   <label style={{ float: 'left' }}>From</label>
   <input
     ref={i => {
       this.reportDateStartedField = i
       }}
     onChange={this.handleFieldChange.bind(this)}
     type="date"
     name="reportDateStarted"
     value={filters.reportDateStarted}
     max={todayDate}
     style={{ fontSize: '0.9em' }}
    />

Upvotes: 2

Views: 11302

Answers (3)

Suraj Neupane
Suraj Neupane

Reputation: 509

I had a similar issue with react js.

When I change date, app does not made change. It's forzen current date.

I have solved this issue by using onFocus instead of onBlur or onClick since datepicker automatically focuses on text field which does made the change (in my case). Also, use onChange on top of onFocus if needed.

<Form.Field>
   <label style={{ float: 'left' }}>From</label>
   <input
     ref={i => {
       this.reportDateStartedField = i
       }}
     onFocus={this.handleFieldChange}
     onChange={this.handleFieldChange}
     type="date"
     name="reportDateStarted"
     defaultValue={filters.reportDateStarted}
     max={todayDate}
     style={{ fontSize: '0.9em' }}
    />

I hope it helps.

Upvotes: 1

Rishabh
Rishabh

Reputation: 1213

I would not call it a performance issue. Since react follows one way data binding, it is up the the developer to decide when to call the render(or defer rendering). Virtual DOM should be in sync.

On the side note you could use 'onBlur' instead of 'onChange' to trigger change only when user has finished typing and focused out.

<Form.Field>
   <label style={{ float: 'left' }}>From</label>
   <input
     ref={i => {
       this.reportDateStartedField = i
       }}
     onBlur={this.handleFieldChange.bind(this)}
     type="date"
     name="reportDateStarted"
     defaultValue={filters.reportDateStarted}
     max={todayDate}
     style={{ fontSize: '0.9em' }}
    />

In above case the input will be 'uncontrolled' (defaultValue) since react is not aware of the change until user focus out of the input.

Upvotes: 1

Linschlager
Linschlager

Reputation: 1639

Probably the easiest solution would be to not use the onChange event to fetch data but only use it to control the input and have a button onClick to do the fetching.

Upvotes: 1

Related Questions