From 4f889e88201585dfdee653b57f0a2cd599c8a155 Mon Sep 17 00:00:00 2001 From: Andre Landgraf Date: Thu, 13 Jun 2019 23:11:07 +0200 Subject: [PATCH] show matching items on click if currentInput --- package.json | 2 +- src/DataListInput.jsx | 28 ++++++++++++++++++++-------- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/package.json b/package.json index 1de41cb..2016db0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "react-datalist-input", - "version": "1.1.19", + "version": "1.1.21", "description": "This package provides a react component as follows: an input field with a drop down menu to pick a possible option based on the current input.", "main": "./lib/DataListInput.js", "license": "MIT", diff --git a/src/DataListInput.jsx b/src/DataListInput.jsx index 366d67a..9c56365 100644 --- a/src/DataListInput.jsx +++ b/src/DataListInput.jsx @@ -60,10 +60,14 @@ class DataListInput extends React.Component { } onClickInput = () => { - const { currentInput, visible, matchingItems } = this.state; - const { requiredInputLength, dropDownLength, items } = this.props; + const { currentInput, visible } = this.state; + const { requiredInputLength, dropDownLength, items, match } = this.props; const reachedRequiredLength = currentInput.length >= requiredInputLength; if ( reachedRequiredLength && !visible ) { + const matchingItems = items.filter( ( item ) => { + if ( typeof ( match ) === typeof ( Function ) ) { return match( currentInput, item ); } + return this.match( currentInput, item ); + } ); const displayableItems = matchingItems.length ? matchingItems : items.slice( 0, dropDownLength ) this.setState( { visible: true, matchingItems: displayableItems, focusIndex: 0, } ); @@ -106,7 +110,7 @@ class DataListInput extends React.Component { * @param item * @returns {boolean} */ - match = ( currentInput, item ) => item.contains( currentInput) && item + match = ( currentInput, item ) => item .label.substr( 0, currentInput.length ).toUpperCase() === currentInput.toUpperCase(); /** @@ -204,13 +208,21 @@ class DataListInput extends React.Component { onSelect( selectedItem ); }; + renderMatchingLabel = ( currentInput, item ) => ( + + {item.label.substr( 0, this.indexOfMatch( currentInput, item ) ) } + + { item.label.substr( this.indexOfMatch( currentInput, item ), currentInput.length ) } + + { item.label.substr( this.indexOfMatch( currentInput, item ) + currentInput.length ) } + + ); + renderItemLabel = ( currentInput, item ) => ( - {item.label.substr( 0, this.indexOfMatch( currentInput, item ) )} - - {item.label.substr( this.indexOfMatch( currentInput, item ), currentInput.length )} - - {item.label.substr( this.indexOfMatch( currentInput, item ) + currentInput.length )} + { this.indexOfMatch( currentInput, item ) > 0 + ? this.renderMatchingLabel( currentInput, item ) + : item.label } )