diff --git a/README.md b/README.md index 64470ef..a95398b 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,10 @@ const list = [{ list={list} keys={['author', 'title']} width={430} - onSelect={action('selected')} + onSelect={(newSelectedItem) => { + // Local state setter defined elsewhere + setSelectedItem(newSelectedItem) + }} /> ``` @@ -38,7 +41,10 @@ const list = [{ list={list} keys={['author', 'title']} width={430} - onSelect={action('selected')} + onSelect={(newSelectedItem) => { + // Local state setter defined elsewhere + setSelectedItem(newSelectedItem) + }} resultsTemplate={(props, state, styles, clickHandler) => { return state.results.map((val, i) => { const style = state.selectedIndex === i ? styles.selectedResultStyle : styles.resultsStyle; @@ -77,6 +83,7 @@ onSelect| noop | Function to be executed on selection of any result. keyForDisplayName|title|The key which should be used for list item text. keys|all[Array]|List of properties that will be searched. This also supports nested properties. list|null|Array of properties to be filtered. +maxResults|10|Max number of results to show at once. placeholder|'Search'|Placeholder of the searchbox resultsTemplate| Func | Template of the dropdown divs shouldShowDropdownAtStart|false|Allow the searchbox to act as a `filter` dropdown with initial values. Yields all results when the search value is blank. diff --git a/src/index.js b/src/index.js index 4c98c13..8de5dd7 100644 --- a/src/index.js +++ b/src/index.js @@ -127,7 +127,6 @@ export default class FuzzySearch extends Component { isOpen: !this.props.shouldShowDropdownAtStart, results: [], selectedIndex: 0, - selectedValue: {}, value: '', }; this.handleChange = this.handleChange.bind(this); @@ -201,33 +200,33 @@ export default class FuzzySearch extends Component { // Handle ENTER } else if (e.keyCode === 13) { - if (results[selectedIndex]) { - this.props.onSelect(results[this.state.selectedIndex]); - this.setState({ - selectedValue: results[this.state.selectedIndex], - }); - } - this.setState({ - results: [], - selectedIndex: 0, - value: results[this.state.selectedIndex].item ? results[this.state.selectedIndex].item.value : '', - }); + this.selectItem(); } } - handleMouseClick(clickedIndex) { + selectItem(index) { const { results } = this.state; - - if (results[clickedIndex]) { - this.props.onSelect(results[clickedIndex]); + const selectedIndex = index || this.state.selectedIndex; + const result = results[selectedIndex]; + if (result) { + // send result to onSelectMethod + this.props.onSelect(result); + // and set it as input value + this.setState({ + value: result[this.props.keyForDisplayName], + }); } + // hide dropdown this.setState({ results: [], selectedIndex: 0, - value: results[this.state.selectedIndex].item ? results[this.state.selectedIndex].item.value : '', }); } + handleMouseClick(clickedIndex) { + this.selectItem(clickedIndex); + } + render() { const { autoFocus,