Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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