1.0.0 • Published 1 year ago

autocomplete-searchbox v1.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
1 year ago

AutocompleteSearchBox Component

The AutocompleteSearchBox component is a reusable React component that provides a search box with autocomplete functionality. It can fetch suggestions from an API or a local JSON file based on the provided configuration.

Installation

To use the AutocompleteSearchBox component, install it in your React project:

npm install autocomplete-searchbox

Usage

Import the AutocompleteSearchBox component in your React component:

import React from 'react';
import AutocompleteSearchBox from 'autocomplete-searchbox';

Define a Data Fetching Functions

const fetchSuggestions = async (query, sourceType = 'api', jsonData = null) => {
  if (sourceType === 'api') {
    const response = await fetch(`https://api.example.com/search?q=${query}`);
    const data = await response.json();
    return data.results; // Adjust this according to your API response structure
  } else if (sourceType === 'json' && jsonData) {
    const filteredData = jsonData.filter(item => item.toLowerCase().includes(query.toLowerCase()));
    return filteredData;
  } else {
    throw new Error('Invalid source type or missing JSON data');
  }
};

Example 1: Fetch suggestions from a local JSON file

import jsonData from './data.json'; // Import the JSON file

const App = () => {
  return (
    <div>
      <h1>Autocomplete Search Box</h1>
      <AutocompleteSearchBox 
        suggestions={fetchSuggestions} 
        sourceType="json" 
        jsonData={jsonData}
        placeholder="Search for items..." 
        debounceTime={300}
        onSuggestionSelect={(suggestion) => console.log('Selected:', suggestion)}
      />
    </div>
  );
};

Example 2: Fetch suggestions from an API

const App = () => {
  return (
    <div>
      <h1>Autocomplete Search Box</h1>
      <AutocompleteSearchBox 
        fetchSuggestions={fetchSuggestions} 
        sourceType="api" 
        placeholder="Search for items..." 
        debounceTime={300}
        onSuggestionSelect={(suggestion) => console.log('Selected:', suggestion)}
      />
    </div>
  );
};

Props

PropTypeDefaultDescription
fetchSuggestionsfunctionrequiredFunction to fetch suggestions based on the query.
sourceTypestring'api'Type of data source: 'api' or 'json'.
jsonDataarraynullArray of JSON data to use when 'sourceType' is 'json'.
placeholderstring'Search...'Placeholder text for the search input.
debounceTimenumber300Placeholder text for the search input.
onSuggestionSelectfunctionnullFunction to handle the selection of a suggestion.
1.0.0

1 year ago