Skip to content

Commit

Permalink
Fix EuiFieldSearch's onChange call so it is always called with the Ev…
Browse files Browse the repository at this point in the history
…ent (#2764)

* Fix EuiFieldSearch's onChange call so it is always called with the Event

* changelog

* Actually trigger the browser's change event handling
  • Loading branch information
chandlerprall authored Jan 16, 2020
1 parent 123cb83 commit 3400667
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
## [`master`](https://github.com/elastic/eui/tree/master)

No public interface changes since `18.2.0`.
**Bug fixes**

- Fixed `EuiFieldSearch`'s trigger of `onChange` when clearing the field value ([#2764](https://github.com/elastic/eui/pull/2764))

## [`18.2.0`](https://github.com/elastic/eui/tree/v18.2.0)

Expand Down
2 changes: 1 addition & 1 deletion src-docs/src/views/form_controls/field_search.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export default class extends Component {

onChange = e => {
this.setState({
value: e === '' ? '' : e.target.value,
value: e.target.value,
});
};

Expand Down
32 changes: 31 additions & 1 deletion src/components/form/field_search/field_search.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,37 @@ export class EuiFieldSearch extends Component {
}

onClear = () => {
this.props.onChange('');
// clear the field's value

// 1. React doesn't listen for `change` events, instead it maps `input` events to `change`
// 2. React only fires the mapped `change` event if the element's value has changed
// 3. An input's value is, in addition to other methods, tracked by intercepting element.value = '...'
//
// So we have to go below the element's value setter to avoid React intercepting it,
// only then will React treat the value as different and fire its `change` event
//
// https://stackoverflow.com/questions/23892547/what-is-the-best-way-to-trigger-onchange-event-in-react-js
const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
window.HTMLInputElement.prototype,
'value'
).set;
nativeInputValueSetter.call(this.inputElement, '');

// dispatch input event, with IE11 support/fallback
if ('Event' in window && typeof Event === 'function') {
const event = new Event('input', {
bubbles: true,
cancelable: false,
});
this.inputElement.dispatchEvent(event);
} else {
// IE11
const event = document.createEvent('Event');
event.initEvent('input', true, false);
this.inputElement.dispatchEvent(event);
}

// set focus on the search field
this.inputElement.focus();
};

Expand Down

0 comments on commit 3400667

Please sign in to comment.