Evaficy

Building React Excellence

banner hexa

AutocompletePro: Advanced React Autocomplete Component

AutocompletePro: Advanced React Autocomplete Component

Building modern web applications often requires sophisticated search and selection interfaces. Today, we’re excited to introduce AutocompletePro – a feature-rich, highly customizable React autocomplete component that goes far beyond basic text matching.

Why Another Autocomplete Component?

While there are many autocomplete libraries available, most fall short when it comes to advanced search capabilities and rich user experiences. AutocompletePro addresses these limitations by providing:

  • Multiple search algorithms including fuzzy matching for typo tolerance
  • Rich visual results with images, descriptions, and metadata
  • Smart categorization and trending/recent indicators
  • Async data loading with debounced search
  • Multi-select support with elegant tag management
  • Fully customizable rendering and styling

Key Features

🔍 Advanced Search Algorithms

AutocompletePro supports four different search algorithms:

  • Exact: Traditional substring matching
  • Fuzzy: Levenshtein distance-based matching for typo tolerance
  • Semantic: Word-based matching across multiple fields
  • Hybrid: Combines exact and fuzzy matching for optimal results

🎨 Rich Visual Interface

  • Display images, descriptions, and metadata for each option
  • Category grouping with visual separators
  • Trending and recent indicators with icons
  • Popularity scoring with star ratings
  • Syntax highlighting for matching text

⚡ Performance Optimized

  • Debounced search to reduce API calls
  • Virtual scrolling for large datasets
  • Memoized calculations to prevent unnecessary re-renders
  • Efficient keyboard navigation

🛠 Highly Customizable

  • Custom option and tag renderers
  • Configurable search behavior
  • Flexible styling with Tailwind CSS
  • Comprehensive TypeScript support

Installation

npm install react-autocomplete-pro
# or
yarn add react-autocomplete-pro

Demo:

Basic Usage

Simple Single Select

import React, { useState } from 'react';
import { AutocompletePro, AutocompleteOption } from 'react-autocomplete-pro';

const options: AutocompleteOption[] = [
  { id: '1', label: 'iPhone 15 Pro', value: 'iphone-15-pro' },
  { id: '2', label: 'Samsung Galaxy S24', value: 'samsung-s24' },
  { id: '3', label: 'MacBook Pro M3', value: 'macbook-pro-m3' }
];

function BasicExample() {
  const [selected, setSelected] = useState<AutocompleteOption | undefined>();

  return (
    <AutocompletePro
      options={options}
      value={selected}
      onChange={setSelected}
      placeholder="Search products..."
    />
  );
}

Multi-Select with Categories

function MultiSelectExample() {
  const [selected, setSelected] = useState<AutocompleteOption[]>([]);

  const options: AutocompleteOption[] = [
    {
      id: '1',
      label: 'iPhone 15 Pro',
      value: 'iphone-15-pro',
      category: 'Smartphones',
      description: 'Latest Apple smartphone with titanium design',
      image: 'https://example.com/iphone.jpg',
      popularity: 95,
      trending: true
    },
    // ... more options
  ];

  return (
    <AutocompletePro
      options={options}
      value={selected}
      onChange={setSelected}
      multiple={true}
      showCategories={true}
      showTrending={true}
      groupBy={(option) => option.category}
      placeholder="Select multiple products..."
    />
  );
}

Async Search with Fuzzy Matching

function AsyncExample() {
  const handleAsyncSearch = async (query: string): Promise<AutocompleteOption[]> => {
    const response = await fetch(`/api/search?q=${query}`);
    return response.json();
  };

  return (
    <AutocompletePro
      options={[]}
      onSearch={handleAsyncSearch}
      searchConfig={{
        algorithm: 'fuzzy',
        fuzzyThreshold: 0.5,
        debounceMs: 300,
        minQueryLength: 2
      }}
      placeholder="Type to search (handles typos)..."
    />
  );
}

API Reference

AutocompleteOption Interface

interface AutocompleteOption {
  id: string;                    // Unique identifier
  label: string;                 // Display text
  value: string;                 // Form value
  category?: string;             // Group category
  description?: string;          // Additional description
  image?: string;                // Image URL
  metadata?: Record<string, any>; // Custom data
  popularity?: number;           // Score 0-100
  recent?: boolean;              // Recent search indicator
  trending?: boolean;            // Trending indicator
}

SearchConfig Interface

interface SearchConfig {
  algorithm: 'fuzzy' | 'exact' | 'semantic' | 'hybrid';
  fuzzyThreshold: number;        // 0-1, lower = more lenient
  minQueryLength: number;        // Minimum chars to trigger search
  maxResults: number;            // Maximum results to show
  debounceMs: number;            // Search delay in milliseconds
  caseSensitive: boolean;        // Case-sensitive matching
  accentSensitive: boolean;      // Accent-sensitive matching
}

Component Props

Prop Type Default Description
options AutocompleteOption[] [] Static options array
value AutocompleteOption | AutocompleteOption[] undefined Selected value(s)
onChange (selected) => void undefined Selection change handler
onSearch (query: string) => Promise<AutocompleteOption[]> undefined Async search function
placeholder string "Search..." Input placeholder
multiple boolean false Enable multi-select
searchConfig Partial<SearchConfig> {} Search configuration
renderOption (option, isHighlighted) => ReactNode undefined Custom option renderer
renderTag (option, onRemove) => ReactNode undefined Custom tag renderer
groupBy (option) => string undefined Grouping function
filterBy string[] ['label', 'value', 'description'] Fields to search
showCategories boolean true Show category labels
showRecent boolean true Show recent indicators
showTrending boolean true Show trending indicators
className string "" Container CSS class
disabled boolean false Disable component
loading boolean false Show loading state

Advanced Examples

Custom Option Renderer

const customRenderOption = (option: AutocompleteOption, isHighlighted: boolean) => (
  <div className={`p-4 flex items-center ${isHighlighted ? 'bg-blue-50' : ''}`}>
    <img src={option.image} className="w-12 h-12 rounded-full mr-3" />
    <div>
      <div className="font-bold">{option.label}</div>
      <div className="text-sm text-gray-600">{option.description}</div>
      <div className="text-xs text-blue-600">{option.category}</div>
    </div>
  </div>
);

<AutocompletePro
  options={options}
  renderOption={customRenderOption}
/>

Custom Tag Renderer

const customRenderTag = (option: AutocompleteOption, onRemove: () => void) => (
  <span className="inline-flex items-center px-3 py-1 rounded-full bg-gradient-to-r from-blue-500 to-purple-600 text-white text-sm">
    <img src={option.image} className="w-4 h-4 rounded-full mr-2" />
    {option.label}
    <button onClick={onRemove} className="ml-2 hover:text-gray-200">
      ×
    </button>
  </span>
);

<AutocompletePro
  options={options}
  multiple={true}
  renderTag={customRenderTag}
/>

Semantic Search Configuration

<AutocompletePro
  options={productOptions}
  searchConfig={{
    algorithm: 'semantic',
    minQueryLength: 3,
    maxResults: 15,
    debounceMs: 500
  }}
  filterBy={['label', 'description', 'category', 'metadata.tags']}
/>

Keyboard Navigation

AutocompletePro provides full keyboard accessibility:

  • Arrow Keys: Navigate through options
  • Enter: Select highlighted option
  • Escape: Close dropdown and blur input
  • Tab: Close dropdown and move to next element

Styling and Customization

The component uses Tailwind CSS classes and can be fully customized:

<AutocompletePro
  className="max-w-md"
  options={options}
  // Custom styles will be applied to container
/>

For deeper customization, you can override the default classes or provide custom renderers.

Performance Tips

  1. Use debouncing for async searches to reduce API calls
  2. Limit results with maxResults for better performance
  3. Implement server-side filtering for large datasets
  4. Use memoization for expensive calculations in custom renderers

Browser Support

AutocompletePro supports all modern browsers:

  • Chrome 60+
  • Firefox 60+
  • Safari 12+
  • Edge 79+

TypeScript Support

The component is built with TypeScript and provides full type safety:

import { AutocompletePro, AutocompleteOption, SearchConfig } from 'react-autocomplete-pro';

// Full type inference and checking
const MyComponent: React.FC = () => {
  const [value, setValue] = useState<AutocompleteOption>();
  
  return (
    <AutocompletePro
      options={typedOptions}
      value={value}
      onChange={setValue} // Fully typed
    />
  );
};

License

MIT License


AutocompletePro makes it easy to build sophisticated search interfaces that users love. With its powerful search algorithms, rich visual features, and extensive customization options, it’s the perfect choice for modern React applications.

Try it out in your next project and let us know what you think!