Skip to content
This repository was archived by the owner on Jul 19, 2019. It is now read-only.

Commit 987f738

Browse files
committed
[fixed] Reset highlightedIndex when it's outside of items.length
1 parent 2fbafa6 commit 987f738

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

lib/Autocomplete.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,17 @@ let Autocomplete = React.createClass({
6262
this._performAutoCompleteOnKeyUp = false
6363
},
6464

65-
componentWillReceiveProps () {
65+
componentWillReceiveProps (nextProps) {
6666
this._performAutoCompleteOnUpdate = true
67+
// If `items` has changed we want to reset `highlightedIndex`
68+
// since it probably no longer refers to a relevant item
69+
if (this.props.items !== nextProps.items ||
70+
// The entries in `items` may have been changed even though the
71+
// object reference remains the same, double check by seeing
72+
// if `highlightedIndex` points to an existing item
73+
this.state.highlightedIndex >= nextProps.items.length) {
74+
this.setState({ highlightedIndex: null })
75+
}
6776
},
6877

6978
componentDidUpdate (prevProps, prevState) {

lib/__tests__/Autocomplete-test.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,21 @@ describe('Autocomplete acceptance tests', () => {
6060

6161
});
6262

63+
it('should reset `highlightedIndex` when `items` changes', () => {
64+
autocompleteWrapper.setState({ highlightedIndex: 10 });
65+
autocompleteWrapper.setProps({ items: [] });
66+
expect(autocompleteWrapper.state('highlightedIndex')).toBe(null);
67+
});
68+
69+
it('should reset `highlightedIndex` when it falls outside of possible `items` range', () => {
70+
const items = getStates();
71+
autocompleteWrapper.setProps({ items });
72+
autocompleteWrapper.setState({ highlightedIndex: 10 });
73+
items.length = 5;
74+
autocompleteWrapper.setProps({ items });
75+
expect(autocompleteWrapper.state('highlightedIndex')).toBe(null);
76+
});
77+
6378
});
6479

6580
// Event handler unit tests

0 commit comments

Comments
 (0)