From db5ed04e9d4524e59ab6852458bf4f260dd9f371 Mon Sep 17 00:00:00 2001 From: tjphopkins Date: Thu, 26 Apr 2018 11:12:21 +0100 Subject: [PATCH] Allow for custom suggestions component --- lib/ReactTags.js | 10 ++++++++-- lib/Suggestions.js | 8 +++++++- spec/ReactTags.spec.js | 19 +++++++++++++++++++ 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/lib/ReactTags.js b/lib/ReactTags.js index ce60c40..1736941 100644 --- a/lib/ReactTags.js +++ b/lib/ReactTags.js @@ -210,7 +210,8 @@ class ReactTags extends React.Component { id={this.props.id} ref={(c) => { this.suggestions = c }} expanded={expanded} - addTag={this.addTag.bind(this)} /> + addTag={this.addTag.bind(this)} + suggestionComponent={this.props.suggestionComponent} /> ) @@ -228,7 +229,8 @@ ReactTags.defaultProps = { maxSuggestionsLength: 6, allowNew: false, allowBackspace: true, - tagComponent: null + tagComponent: null, + suggestionComponent: null } ReactTags.propTypes = { @@ -251,6 +253,10 @@ ReactTags.propTypes = { tagComponent: PropTypes.oneOfType([ PropTypes.func, PropTypes.element + ]), + suggestionComponent: PropTypes.oneOfType([ + PropTypes.func, + PropTypes.element ]) } diff --git a/lib/Suggestions.js b/lib/Suggestions.js index 5622d5c..6bcf66f 100644 --- a/lib/Suggestions.js +++ b/lib/Suggestions.js @@ -6,6 +6,10 @@ function markIt (name, query) { return name.replace(regexp, '$&') } +const DefaultSuggestionComponent = ({ item, query }) => ( + +) + class Suggestions extends React.Component { onMouseDown (item, e) { // focus is shifted on mouse down but calling preventDefault prevents this @@ -18,6 +22,8 @@ class Suggestions extends React.Component { return null } + const SuggestionComponent = this.props.suggestionComponent || DefaultSuggestionComponent + const options = this.props.options.map((item, index) => { const key = `${this.props.id}-${index}` const classNames = [] @@ -38,7 +44,7 @@ class Suggestions extends React.Component { className={classNames.join(' ')} aria-disabled={item.disabled === true} onMouseDown={this.onMouseDown.bind(this, item)}> - + ) }) diff --git a/spec/ReactTags.spec.js b/spec/ReactTags.spec.js index 4090765..2c42802 100644 --- a/spec/ReactTags.spec.js +++ b/spec/ReactTags.spec.js @@ -325,6 +325,25 @@ describe('React Tags', () => { expect(input.value).toEqual('') expect(document.activeElement).toEqual(input) }) + + it('can render a custom suggestion component when provided', () => { + const CustomSuggestion = ({ item, query }) => ( + React.createElement( + 'div', { className: 'custom-suggestion' }, item.name) + ) + + createInstance({ + tags: [], + suggestions: fixture, + suggestionComponent: CustomSuggestion + }) + + type(query) + + expect($('ul[role="listbox"]')).toBeTruthy() + + expect($$('.custom-suggestion').length).toEqual(3) + }) }) describe('tags', () => {