react-autosuggest

repository·master·Indexed 26 days ago

https://github.com/moroshko/react-autosuggest

A WAI-ARIA compliant autocomplete component for React applications (version 10.1.0). It provides full control over suggestion rendering, input props, and suggestion retrieval, including asynchronous support. The component supports multi-section grouped suggestions, custom theme styling via react-themeable, and a controlled component pattern for managing input values and suggestion lists.

Tokens
3.3K
Snippets
8
Records
15
Agent score
90%

What's inside react-autosuggest

  1. Run the React Autosuggest demo locally

    master

    To run the project's demo environment for development and testing, install the dependencies and start the development server using npm. Once running, you can view the demo at http://localhost:3000/demo/dist/index.html.

    npm install
    npm start
  2. Install react-autosuggest

    master

    You can install react-autosuggest using npm or yarn, or use the standalone UMD build via a script tag.

    yarn add react-autosuggest
    npm install react-autosuggest --save
    <script src="https://unpkg.com/react-autosuggest/dist/standalone/autosuggest.js"></script>
  3. Handle multiple Autosuggest instances with unique IDs

    master

    If you render multiple Autosuggest components on a single page, you must provide a unique id prop to each one. This is required for the component to correctly set ARIA attributes for accessibility.

    <Autosuggest id="source" ... />
    <Autosuggest id="destination" ... />
  4. Use multiSection mode for grouped suggestions

    master

    To display suggestions in multiple sections with titles, set multiSection={true}. When using this mode, you must implement two additional props:

    1. renderSectionTitle: Defines how section titles are rendered. Signature: (section) => string | ReactElement.
    2. getSectionSuggestions: Defines where to find the suggestions for a specific section. Signature: (section) => Array.

    Example suggestion structure for multiSection:

    const suggestions = [
      {
        title: "A",
        suggestions: [
          { id: "100", text: "Apple" },
          { id: "101", text: "Apricot" }
        ]
      },
      {
        title: "B",
        suggestions: [
          { id: "102", text: "Banana" }
        ]
      }
    ];
  5. Style Autosuggest with a custom theme

    master

    Autosuggest uses react-themeable. You can provide a theme object to map component parts to your own CSS classes. If no theme is provided, it defaults to classes prefixed with react-autosuggest__.

    Default theme keys:

    • container / containerOpen
    • input / inputOpen / inputFocused
    • suggestionsContainer / suggestionsContainerOpen
    • suggestionsList
    • suggestion / suggestionFirst / suggestionHighlighted
    • sectionContainer / sectionContainerFirst
    • sectionTitle
  6. Limit suggestions container scrolling to prevent page scroll

    master

    To prevent the page from scrolling when the suggestions container reaches its scroll boundaries, wrap the container in react-isolated-scroll. You must intercept the ref from containerProps and pass the isolatedScroll.component to the original ref via the renderSuggestionsContainer prop.

    import IsolatedScroll from 'react-isolated-scroll';
    
    function renderSuggestionsContainer({ containerProps, children }) {
      const { ref, ...restContainerProps } = containerProps;
      const callRef = isolatedScroll => {
        if (isolatedScroll !== null) {
          ref(isolatedScroll.component);
        }
      };
    
      return (
        <IsolatedScroll ref={callRef} {...restContainerProps}>
          {children}
        </IsolatedScroll>
      );
    }
    
    <Autosuggest renderSuggestionsContainer={renderSuggestionsContainer} ... />
  7. Access the input element via ref

    master

    The input element is exposed on the Autosuggest instance via the input property. To access it, use a ref callback to capture the instance and store the input property.

    function storeInputReference(autosuggest) {
      if (autosuggest !== null) {
        this.input = autosuggest.input;
      }
    }
    
    <Autosuggest ref={storeInputReference} ... />
  8. Basic Usage of Autosuggest

    master

    To use Autosuggest, you must treat it as a controlled component. You need to manage the input value and the suggestions list in your component state. You must provide handlers for fetching and clearing suggestions, as well as functions to determine the suggestion value and how to render each suggestion.

    import React from 'react';
    import Autosuggest from 'react-autosuggest';
    
    // Data source
    const languages = [
      { name: 'C', year: 1972 },
      { name: 'Elm', year: 2012 },
    ];
    
    // Logic to filter suggestions
    const getSuggestions = value => {
      const inputValue = value.trim().toLowerCase();
      const inputLength = inputValue.length;
      return inputLength === 0 ? [] : languages.filter(lang =>
        lang.name.toLowerCase().slice(0, inputLength) === inputValue
      );
    };
    
    // Logic to get the string value from a suggestion object
    const getSuggestionValue = suggestion => suggestion.name;
    
    // Logic to render the suggestion UI
    const renderSuggestion = suggestion => (
      <div>
        {suggestion.name}
      </div>
    );
    
    class Example extends React.Component {
      constructor() {
        super();
        this.state = {
          value: '',
          suggestions: []
        };
      }
    
      onChange = (event, { newValue }) => {
        this.setState({ value: newValue });
      };
    
      onSuggestionsFetchRequested = ({ value }) => {
        this.setState({ suggestions: getSuggestions(value) });
      };
    
      onSuggestionsClearRequested = () => {
        this.setState({ suggestions: [] });
      };
    
      render() {
        const { value, suggestions } = this.state;
    
        const inputProps = {
          placeholder: 'Type a programming language',
          value,
          onChange: this.onChange
        };
    
        return (
          <Autosuggest
            suggestions={suggestions}
            onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
            onSuggestionsClearRequested={this.onSuggestionsClearRequested}
            getSuggestionValue={getSuggestionValue}
            renderSuggestion={renderSuggestion}
            inputProps={inputProps}
          />
        );
      }
    }
  9. Configure inputProps.onChange

    master

    Since Autosuggest is a controlled component, you must provide an onChange handler within inputProps. The handler receives the event and an object describing how the change occurred.

    Possible method values:

    • 'down': User pressed Down key.
    • 'up': User pressed Up key.
    • 'escape': User pressed Escape.
    • 'enter': User pressed Enter.
    • 'click': User clicked/tapped a suggestion.
    • 'type': User typed, pasted, or used backspace.
  10. Customize the suggestions container

    master

    Use renderSuggestionsContainer to customize the container wrapping the suggestions (e.g., adding custom text or controlling scrolling).

    Important: You must pass containerProps to the topmost element returned. If you return a composite component (like IsolatedScroll), you must call containerProps.ref with the topmost element's ref.

    Signature: ({ containerProps, children, query }) => ReactElement

    function renderSuggestionsContainer({ containerProps, children, query }) {
      return (
        <div {...containerProps}>
          {children}
          <div>
            Press Enter to search <strong>{query}</strong>
          </div>
        </div>
      );
    }
  11. Configure the Autosuggest component props

    master

    The Autosuggest component is highly configurable via props.

    Required Props

    • suggestions: An Array of items to display. Items can be plain objects for a list or section objects for multiSection mode.
    • onSuggestionsFetchRequested: Function called when suggestions need to be recalculated. Signature: ({ value, reason }).
    • onSuggestionsClearRequested: Function called to clear suggestions (set to []). Required unless alwaysRenderSuggestions={true}.
    • getSuggestionValue: Function to map a suggestion to an input string. Signature: (suggestion) => string.
    • renderSuggestion: Pure function to render a single suggestion. Signature: (suggestion, { query, isHighlighted }).
    • inputProps: Object containing at least value and onChange for the controlled input.

    Common Optional Props

    • onSuggestionSelected: Called when a suggestion is picked. Signature: (event, { suggestion, suggestionValue, suggestionIndex, sectionIndex, method }).
    • shouldRenderSuggestions: Function to control when the list appears. Signature: (value, reason) => boolean.
    • multiSection: Boolean to enable grouped suggestions.
    • theme: Object to provide custom CSS class names for styling.