Convert Figma logo to code with AI

algolia logoautocomplete

🔮 Fast and full-featured autocomplete library

5,016
330
5,016
48

Top Related Projects

typeahead.js is a fast and fully-featured autocomplete library

Simple autocomplete pure vanilla Javascript library.

Ultra lightweight, usable, beautiful autocomplete with zero dependencies.

Ajax Autocomplete for jQuery allows you to easily create autocomplete/autosuggest boxes for text input fields

WAI-ARIA compliant React autosuggest component

Quick Overview

Algolia's Autocomplete is a JavaScript library that provides fast, customizable, and accessible autocomplete experiences for search interfaces. It offers a flexible and powerful solution for implementing autocomplete functionality in web applications, with support for various data sources and customization options.

Pros

  • Highly customizable and extensible
  • Excellent performance and speed
  • Accessible by default, following ARIA guidelines
  • Supports multiple data sources and plugins

Cons

  • Learning curve for advanced customizations
  • Requires additional setup for complex use cases
  • Limited built-in styling options
  • Dependency on Algolia for some features

Code Examples

Basic usage with local data:

import { autocomplete } from '@algolia/autocomplete-js';

autocomplete({
  container: '#autocomplete',
  placeholder: 'Search...',
  getSources({ query }) {
    return [{
      sourceId: 'fruits',
      getItems() {
        return ['apple', 'banana', 'cherry'].filter(fruit => 
          fruit.toLowerCase().includes(query.toLowerCase())
        );
      },
      templates: {
        item({ item }) {
          return item;
        },
      },
    }];
  },
});

Using with Algolia search:

import algoliasearch from 'algoliasearch/lite';
import { autocomplete, getAlgoliaResults } from '@algolia/autocomplete-js';

const searchClient = algoliasearch('YOUR_APP_ID', 'YOUR_SEARCH_API_KEY');

autocomplete({
  container: '#autocomplete',
  placeholder: 'Search products',
  getSources({ query }) {
    return [{
      sourceId: 'products',
      getItems() {
        return getAlgoliaResults({
          searchClient,
          queries: [{
            indexName: 'products',
            query,
          }],
        });
      },
      templates: {
        item({ item, components }) {
          return `
            <div class="aa-ItemWrapper">
              <div class="aa-ItemContent">
                <div class="aa-ItemTitle">
                  ${components.Highlight({ hit: item, attribute: 'name' })}
                </div>
              </div>
            </div>
          `;
        },
      },
    }];
  },
});

Custom rendering with React:

import { autocomplete } from '@algolia/autocomplete-js';
import React from 'react';
import { createRoot } from 'react-dom/client';

function Autocomplete(props) {
  const containerRef = React.useRef(null);

  React.useEffect(() => {
    if (!containerRef.current) {
      return undefined;
    }

    const search = autocomplete({
      container: containerRef.current,
      renderer: { createElement, Fragment: React.Fragment },
      render({ children }, root) {
        const reactRoot = createRoot(root);
        reactRoot.render(children);
        return () => reactRoot.unmount();
      },
      ...props,
    });

    return () => {
      search.destroy();
    };
  }, [props]);

  return <div ref={containerRef} />;
}

function App() {
  return (
    <Autocomplete
      placeholder="Search..."
      getSources={({ query }) => [
        {
          sourceId: 'items',
          getItems() {
            return [
              { label: 'Item 1' },
              { label: 'Item 2' },
              { label: 'Item 3' },
            ];
          },
          templates: {
            item({ item }) {
              return <div>{item.label}</div>;
            },
          },
        },
      ]}
    />
  );
}

Getting Started

  1. Install the package:

    npm install @algolia/autocomplete-js
    
  2. Import and use in your project:

    import { autocomplete } from '@algolia/autocomplete-js';
    import '@algolia/autocomplete-theme-classic';
    
    autocomplete
    

Competitor Comparisons

typeahead.js is a fast and fully-featured autocomplete library

Pros of Typeahead.js

  • Lightweight and fast, with minimal dependencies
  • Extensive customization options for styling and behavior
  • Well-established and battle-tested in production environments

Cons of Typeahead.js

  • No longer actively maintained (last update in 2017)
  • Limited built-in features compared to modern alternatives
  • Requires more manual configuration for advanced use cases

Code Comparison

Typeahead.js:

$('#search-input').typeahead({
  hint: true,
  highlight: true,
  minLength: 1
},
{
  name: 'states',
  source: substringMatcher(states)
});

Autocomplete:

autocomplete({
  container: '#search-input',
  getSources({ query }) {
    return [{
      sourceId: 'products',
      getItems() {
        return getAlgoliaResults({
          searchClient,
          queries: [{ indexName: 'products', query }],
        });
      },
    }];
  },
});

Key Differences

  • Autocomplete offers a more modern API with better TypeScript support
  • Autocomplete provides built-in Algolia integration, while Typeahead.js requires custom implementation
  • Autocomplete has a more active development community and frequent updates
  • Typeahead.js has a simpler setup for basic use cases, but Autocomplete offers more flexibility for complex scenarios

Both libraries serve similar purposes, but Autocomplete is generally more suitable for modern web applications, especially those using Algolia search. Typeahead.js may still be preferred for simpler projects or those with legacy requirements.

Simple autocomplete pure vanilla Javascript library.

Pros of autoComplete.js

  • Lightweight and dependency-free, resulting in a smaller bundle size
  • Offers more customization options for UI and behavior out of the box
  • Provides built-in keyboard navigation and accessibility features

Cons of autoComplete.js

  • Less extensive documentation and community support compared to Autocomplete
  • Fewer advanced features like multi-source search or debouncing
  • May require more manual configuration for complex use cases

Code Comparison

autoComplete.js:

const autoCompleteJS = new autoComplete({
  selector: "#autoComplete",
  data: {
    src: ["Apple", "Banana", "Cherry"],
    cache: true,
  },
  resultItem: {
    highlight: true
  }
});

Autocomplete:

autocomplete({
  container: '#autocomplete',
  getSources({ query }) {
    return [{
      sourceId: 'fruits',
      getItems() {
        return ['Apple', 'Banana', 'Cherry'].filter(item =>
          item.toLowerCase().includes(query.toLowerCase())
        );
      }
    }];
  }
});

Both libraries offer easy-to-use APIs for implementing autocomplete functionality. autoComplete.js provides a more concise setup with built-in highlighting, while Autocomplete offers a more flexible structure for complex scenarios, such as multiple data sources or custom filtering logic.

Ultra lightweight, usable, beautiful autocomplete with zero dependencies.

Pros of Awesomplete

  • Lightweight and dependency-free, with a small footprint (~2KB minified and gzipped)
  • Simple to use with minimal setup required
  • Supports custom item rendering and filtering

Cons of Awesomplete

  • Limited built-in features compared to Autocomplete
  • Less active development and community support
  • Fewer customization options for complex use cases

Code Comparison

Awesomplete:

var input = document.getElementById("myinput");
new Awesomplete(input, {
  list: ["Ada", "Java", "JavaScript", "Brainfuck", "LOLCODE", "Node.js", "Ruby on Rails"]
});

Autocomplete:

autocomplete({
  container: '#search-input',
  getSources({ query }) {
    return [{
      sourceId: 'products',
      getItems() {
        return getAlgoliaResults({
          searchClient,
          queries: [{ indexName: 'products', query }],
        });
      },
    }];
  },
});

Summary

Awesomplete is a lightweight, easy-to-use autocomplete library that's ideal for simple use cases. It's dependency-free and has a small footprint, making it suitable for projects where minimalism is key. However, it lacks some of the advanced features and extensive customization options offered by Autocomplete.

Autocomplete, on the other hand, provides a more robust and feature-rich solution, with better support for complex scenarios, multiple data sources, and advanced customization. It has stronger community support and more frequent updates but comes with a larger footprint and potential dependencies.

Choose Awesomplete for simple, lightweight autocomplete functionality, and Autocomplete for more complex, feature-rich implementations.

Ajax Autocomplete for jQuery allows you to easily create autocomplete/autosuggest boxes for text input fields

Pros of jQuery-Autocomplete

  • Lightweight and simple to implement, especially for jQuery-based projects
  • Supports local and remote data sources out of the box
  • Extensive customization options for appearance and behavior

Cons of jQuery-Autocomplete

  • Dependent on jQuery, which may not be ideal for modern web applications
  • Limited built-in accessibility features compared to Autocomplete
  • Less active development and community support

Code Comparison

jQuery-Autocomplete:

$('#autocomplete').autocomplete({
    serviceUrl: '/api/search',
    onSelect: function(suggestion) {
        console.log('Selected: ' + suggestion.value);
    }
});

Autocomplete:

autocomplete({
    container: '#autocomplete',
    getSources({ query }) {
        return [
            {
                sourceId: 'products',
                getItems() {
                    return getAlgoliaResults({
                        searchClient,
                        queries: [{ indexName: 'products', query }],
                    });
                },
            },
        ];
    },
});

The jQuery-Autocomplete example shows a simpler setup with a single API endpoint, while the Autocomplete example demonstrates integration with Algolia's search client and more flexible source configuration. Autocomplete offers a more modern, modular approach with better TypeScript support and extensibility, making it suitable for complex, large-scale applications. However, jQuery-Autocomplete might be preferable for smaller projects or those already using jQuery, due to its simplicity and ease of integration.

WAI-ARIA compliant React autosuggest component

Pros of react-autosuggest

  • Specifically designed for React applications, ensuring seamless integration
  • Highly customizable with extensive styling options
  • Supports keyboard navigation out of the box

Cons of react-autosuggest

  • Less frequently updated compared to Autocomplete
  • Limited to React ecosystem, not suitable for vanilla JavaScript or other frameworks
  • Requires more setup and configuration for advanced use cases

Code Comparison

react-autosuggest:

import Autosuggest from 'react-autosuggest';

const renderSuggestion = suggestion => (
  <div>{suggestion.name}</div>
);

<Autosuggest
  suggestions={suggestions}
  onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
  onSuggestionsClearRequested={this.onSuggestionsClearRequested}
  getSuggestionValue={getSuggestionValue}
  renderSuggestion={renderSuggestion}
  inputProps={inputProps}
/>

Autocomplete:

import { autocomplete } from '@algolia/autocomplete-js';

autocomplete({
  container: '#autocomplete',
  placeholder: 'Search',
  getSources({ query }) {
    return [
      {
        sourceId: 'products',
        getItems() {
          return getAlgoliaResults({
            searchClient,
            queries: [
              {
                indexName: 'products',
                query,
              },
            ],
          });
        },
        templates: {
          item({ item, components }) {
            return `<div>${item.name}</div>`;
          },
        },
      },
    ];
  },
});

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Autocomplete

A JavaScript library that lets you quickly build autocomplete experiences

Version MIT License

All you need to get started is:

  • A container to inject the experience into
  • Data to fill the autocomplete with
  • Any Virtual DOM solution (JavaScript, Preact, React, Vue, etc.)

The data that populates the autocomplete results are called sources. You can use whatever you want in your sources: a static set of searches terms, search results from an external source like an Algolia index, recent searches, and more.

By configuring just those two required parameters (container and getSources) you can have an interactive autocomplete experience. The library creates an input and provides the interactivity and accessibility attributes, but you're in full control of the DOM elements to output.

Screenshot

Documentation • API • Playground

Installation

The recommended way to get started is with the autocomplete-js package. It includes everything you need to render a JavaScript autocomplete experience.

Otherwise, you can install the autocomplete-core package if you want to build a renderer from scratch.

All Autocomplete packages are available on the npm registry.

yarn add @algolia/autocomplete-js
# or
npm install @algolia/autocomplete-js

If you don't use a package manager, you can use the HTML script element:

<script src="https://cdn.jsdelivr.net/npm/@algolia/autocomplete-js"></script>
<script>
  const { autocomplete } = window['@algolia/autocomplete-js'];
</script>

Usage

To get started, you need a container for your autocomplete to go in. If you don't have one already, you can insert one into your markup:

<div id="autocomplete"></div>

Then, insert your autocomplete into it by calling the autocomplete function and providing the container. It can be a CSS selector or an Element.

Make sure to provide a container (e.g., a div), not an input. Autocomplete generates a fully accessible search box for you.

import { autocomplete } from '@algolia/autocomplete-js';

autocomplete({
  container: '#autocomplete',
  // ...
});

Continue reading our Getting Started guide.

Documentation

The documentation offers a few ways to learn about the Autocomplete library:

  • Read the Core Concepts to learn more about underlying principles, like Sources and State.
  • Follow the Guides to understand how to build common UX patterns.
  • Refer to API reference for a comprehensive list of parameters and options.
  • Try out the Playground where you can fork a basic implementation and play around.

You can find more on the documentation.

Support

Packages

PackageDescriptionDocumentation
autocomplete-jsJavaScript package for AutocompleteDocumentation
autocomplete-coreJavaScript core primitives to build an autocomplete experienceDocumentation
autocomplete-plugin-recent-searchesA plugin to add recent searches to AutocompleteDocumentation
autocomplete-plugin-query-suggestionsA plugin to add query suggestions to AutocompleteDocumentation
autocomplete-plugin-algolia-insightsA plugin to add Algolia Insights to AutocompleteDocumentation
autocomplete-plugin-redirect-urlA plugin to enable redirect URLsDocumentation
autocomplete-plugin-tagsA plugin to manage and display a list of tags in AutocompleteDocumentation
autocomplete-preset-algoliaPresets to use Algolia features with AutocompleteDocumentation
autocomplete-theme-classicClassic theme for AutocompleteDocumentation

Showcase

See the awesome experiences people built with Autocomplete:

DocSearchAlgolia Documentation

Find more in our Showcase.

Sandboxes

Check out sandboxes using Autocomplete.

License

MIT

NPM DownloadsLast 30 Days