UNPKG

react-typeahead-tokenizer

Version:

React-based typeahead and typeahead-tokenizer

101 lines (82 loc) 3.21 kB
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import TypeaheadOption from './option'; class TypeaheadSelector extends Component { constructor(props) { super(props); } _onClick = (result, event) => { return this.props.onOptionSelected(result, event); } render() { // Don't render if there are no options to display if (!this.props.options.length && this.props.allowCustomValues <= 0) { return false; } const classList = classNames({ 'typeahead-selector': this.props.defaultClassNames, [this.props.customClasses.results]: this.props.customClasses.results }); // CustomValue should be added to top of results list with different class name let customValue = null; let customValueOffset = 0; if (this.props.customValue !== null) { customValueOffset++; customValue = ( <TypeaheadOption ref={a => this[this.props.customValue] = a} key={this.props.customValue} hover={this.props.selectionIndex === 0} customClasses={this.props.customClasses} customValue={this.props.customValue} onClick={this._onClick.bind(this, this.props.customValue)} > { this.props.customValue } </TypeaheadOption> ); } const results = this.props.options.map((result, i) => { const uniqueKey = result + '_' + i; return ( <TypeaheadOption ref={a => this[uniqueKey] = a} key={uniqueKey} hover={this.props.selectionIndex === i + customValueOffset} customClasses={this.props.customClasses} onClick={this._onClick.bind(this, result)}> { result } </TypeaheadOption> ); }); if (this.props.areResultsTruncated && this.props.resultsTruncatedMessage !== null) { const resultsTruncatedClassList = classNames({ 'results-truncated': this.props.defaultClassNames, [this.props.customClasses.resultsTruncated]: this.props.customClasses.resultsTruncated }); results.push( <li key='results-truncated' className={resultsTruncatedClassList}> {this.props.resultsTruncatedMessage} </li> ); } return ( <ul className={classList}> { customValue } { results } </ul> ); } } TypeaheadSelector.propTypes = { options: PropTypes.array, allowCustomValues: PropTypes.number, customClasses: PropTypes.object, customValue: PropTypes.string, selectionIndex: PropTypes.number, onOptionSelected: PropTypes.func, defaultClassNames: PropTypes.bool, areResultsTruncated: PropTypes.bool, resultsTruncatedMessage: PropTypes.string } export default TypeaheadSelector;