Get started with react-autosuggest CDN

MIT licensed

React-autosuggest is a popular React library for implementing flexible and customizable autocomplete/suggestion features.

Tags:
  • autosuggest
  • autocomplete
  • auto-suggest
  • auto-complete
  • auto suggest
  • auto complete
  • react autosuggest
  • react autocomplete
  • react auto-suggest
  • react auto-complete
  • react auto suggest
  • react auto complete
  • react-autosuggest
  • react-autocomplete
  • react-auto-suggest
  • react-auto-complete
  • react-component

Stable version

Copied!

How to start using react-autosuggest CDN


import React from 'react';
import Autosuggest from 'autosuggest'; // Import the Autosuggest component from the CDN

const suggestions = [
  'Apple', 'Banana', 'Cherry', 'Date', 'Elderberry', 'Fig', 'Grape',
  'Honeydew', 'Kiwi', 'Lemon', 'Mango', 'Nectarine', 'Orange', 'Peach',
  'Quince', 'Raspberry', 'Strawberry', 'Tangerine', 'Ugli Fruit', 'Violet'
];

class FruitSuggestion extends React.Component {
  render() {
    const { fruit } = this.props;
    return <div>{fruit}</div>;
  }
}

class FruitInput extends React.Component {
  state = {
    value: '',
    suggestions: [],
  };

  onChange = (event, { newValue }) => {
    this.setState({ value: newValue });
  };

  onSuggestionsFetchRequested = ({ value }) => {
    const inputValue = value.trim().toLowerCase();
    const inputLength = inputValue.length;

    this.setState({
      suggestions: inputLength === 0 ? [] : suggestions.slice(0, 10).filter(
        fruit => fruit.toLowerCase().slice(0, inputLength) === inputValue
      ),
    });
  };

  onSuggestionsClearRequested = () => {
    this.setState({ suggestions: [] });
  };

  renderSuggestion = suggestion => <FruitSuggestion fruit={suggestion} />;

  renderSelection = selection => (
    <FruitSuggestion fruit={selection.renderItem.props.fruit} />
  );

  render() {
    const { value, suggestions } = this.state;

    return (
      <Autosuggest
        suggestions={suggestions}
        onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
        onSuggestionsClearRequested={this.onSuggestionsClearRequested}
        getSuggestionValue={suggestion => suggestion.props.fruit}
        onSuggestionSelected={this.handleSuggestionSelected}
        inputValue={value}
        renderSuggestion={this.renderSuggestion}
        renderSelection={this.renderSelection}
        inputProps={{
          placeholder: 'Type a fruit',
          value,
          onChange: this.onChange,
        }}
      />
    );
  }
}

export default FruitInput;

All versions