autocomplete-searchbox
v1.0.0
Published
A reusable autocomplete search box component
Downloads
5
Maintainers
Readme
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
| Prop | Type | Default | Description | | ------------------ | -------- | ----------- | ------------------------------------------------------ | | fetchSuggestions | function | required | Function to fetch suggestions based on the query. | | sourceType | string | 'api' | Type of data source: 'api' or 'json'. | | jsonData | array | null | Array of JSON data to use when 'sourceType' is 'json'. | | placeholder | string | 'Search...' | Placeholder text for the search input. | | debounceTime | number | 300 | Placeholder text for the search input. | | onSuggestionSelect | function | null | Function to handle the selection of a suggestion. |