A react hook to filter data based on various search queries.
npm install react-multi-searchA react hook to filter data based on multiple search queries.
!NPM License
!NPM Version
!npm bundle size
!NPM Type Definitions
- 🗃️ Support for various data types
- 📈 Range queries for numbers and dates
- 📜 Search suggestions
- 📊 Support for categorized data
- ✨ Headless, bring your own UI
- 🌐 TypeScript support
- String
- Can be case-sensitive or case-insensitive (default).
- Exact matches can be done by enclosing the query in double quotes.
- Can come with search suggestions, which is the aggregated possible
values for a specific field.
- Boolean
- Support for various truthy and falsy queries (true, yes, 1, etc.)
or provide your own.
- Number
- Support for range queries with operators: >, >=, <, <=, and !=.
- Date
- Support for range queries with operators like numbers.
- Time and timezone are ignored.
_Other data types will be treated as strings._
To see the hook in action, you can check the Storybook demo.
npm:
``sh`
npm i react-multi-search
yarn:
`sh`
yarn add react-multi-search
`jsx
import { useState } from 'react';
import { useMultiSearch } from 'react-multi-search';
const MyComponent = () => {
const initialData = [
{ name: 'John Doe', age: 20, gender: 'Male' },
{ name: 'Jane Doe', age: 25, gender: 'Female' },
// ...
];
const [filteredData, setFilteredData] = useState([]);
const {
states: {
searchString,
searchField,
searchSuggestions,
searchQueries,
isMenuOpen,
shownMenu,
},
actions: {
clearInput,
addSearchQuery,
deleteSearchQuery,
deleteAllSearchQueries,
onMenuKeyDown,
onSearchFieldSelect,
onAllSearchFieldSelect,
onSearchSuggestionSelect,
openMenu,
},
inputProps,
anchorRef,
listRef,
} = useMultiSearch({
initialData,
setFilteredData,
fields: [
{ value: 'name', label: 'Name' },
{ value: 'age', label: 'Age' },
{ value: 'gender', label: 'Gender', showSearchSuggestions: true },
],
});
return (
<>
{/ search bar ------------------------------------------------------- /}
{/ search queries --------------------------------------------------- /}
}
{/ dropdown menu ---------------------------------------------------- /}
{isMenuOpen && (
{/ ... /}
>
);
};
`
See the demo code for a more comprehensive example.
- initialData (required)T[]
- categorizer
- The initial data to filter. This should be an array of objects without categorization. If you want to categorize your data, use the separate function.
- setFilteredData (required)Dispatch
-
- setState function to update the filtered data.
- Since this is a headless hook, the filtered data should be managed by the consuming component for reusability.
- fields (required)
- (FieldWithSuggestionsFieldWithSuggestions
- The fields to search in. Each item in the array can be of type where all keys should have the value of type string or boolean, or FieldWithoutSuggestions for other data types.
- categorizer(data: T[]) => Record
- initialData
- Function to categorize and group the filtered data.
- This is separated from to optimize performance when filtering.
- showEmptyCategoriesboolean
- false
- Defaults to .categorizer
- Show categories that have no items.
- This is only used when is provided.
- shouldInitializeboolean
- true
- Defaults to .
- Control whether the hook should initialize or not.
- This is useful when you want to delay the initialization of the hook until the data is ready.
- globalSearchReplacementkeyof T
- '_default'
- The field to use for global search when no specific field is selected.
- This is used when the search field is set to .
- overrideExistingQueriesWithSameFieldboolean
-
- Override existing queries with the same field.
- caseSensitiveboolean
- false
- Defaults to .
- Whether the comparison should be case-sensitive or not.
- trueLabelstring
- Yes
- Defaults to .true
- The label for value on search suggestions.
- falseLabelstring
- No
- Defaults to .false
- The label for value on search suggestions.
- truthyValuesstring[]
- ['true', '1', 'on', 'yes', 'y', 't', '✓']
- Defaults to
- A list of truthy values to match against boolean values.
- falsyValuesstring[]
- ['false', '0', 'off', 'no', 'n', 'f', 'x']
- Defaults to
- A list of falsy values to match against boolean values.
- fields[number].value (required){ [K in keyof T]: T[K] extends string | boolean ? K : never; }[keyof T]
- for FieldWithSuggestions{ [K in keyof T]: T[K] extends string | boolean ? never : K; }[keyof T]
- for FieldWithoutSuggestions
- The field to search.
- fields[number].label (required)string
-
- The label for the field.
- fields[number].showSearchSuggestionsboolean
- (default: false)FieldWithoutSuggestions
- Show search suggestions for this field.
- This only applies to
- fields[number].strictSuggestionsboolean
- (default: false)FieldWithoutSuggestions
- Enclose suggestions in double quotes to treat as exact match.
- This only applies to
- fields[number].searchSuggestionsT[FieldWithSuggestions
-
- The search suggestions for this field.
- If provided, it will be used instead of computing the suggestions.
- states - Usable states for the search filter.searchString
- string
-
- The current search string.
- searchFieldstring[]
-
- Selected field to search.
- searchSuggestionsFieldWithSuggestions
-
- Search suggestions for the selected field.
- searchQueries
- SearchQuery
- Current search queries.
- isMenuOpenboolean
-
- Dropdown menu open state.
- shownMenu'fields' | 'searchSuggestions'
-
- The type of dropdown menu currently shown.
- isFilteredboolean
-
- Whether the data is filtered or not.
- isInitializedboolean
-
- Whether the hook is initialized or not.
- actions - Actions to interact with the search filter.clearInput
- () => void
-
- Clear the search input.
- addSearchQuery() => void
-
- Trigger to add the current search string and field as a search query.
- deleteSearchQuery(idx: number) => void
-
- Delete a search query by index.
- deleteAllSearchQueries() => void
-
- Delete all search queries.
- onMenuKeyDown(e: KeyboardEvent
-
- Event handler to handle key down events on the menu.
- onSearchFieldSelect(field: FieldWithSuggestions
-
- Event handler to handle field selection.
- onAllSearchFieldSelect() => void
-
- Event handler to handle "All" field selection.
- onSearchSuggestionSelect(value: string) => void
-
- Event handler to handle search suggestion selection.
- openMenu() => void
-
- Open the dropdown menu.
- closeMenu() => void
-
- Close the dropdown menu.
- inputProps - Props passed to the input element (search bar).onChange
- (e: ChangeEvent
-
- Event handler to handle input change.
- onKeyDown(e: KeyboardEvent
- Enter
- Event handler to handle key down events on the input.
- Includes handling various keys: , Escape, Backspace, ArrowDown, and field selection (:).
- onPaste(e: ClipboardEvent
-
- Event handler to handle paste events on the input.
- Primarily for separating search field and string.
- onFocus() => void
-
- Event handler to handle focus events on the input.
- Used for opening the dropdown menu.
- onBlur() => void
-
- Event handler to handle blur events on the input.
- valuestring
- searchString
- Same as .
- refRefObject
-
- Ref forwarded to the input element.
- anchorRef - Ref forwarded to the anchor element (search bar wrapper).
- listRef - Ref forwarded to the dropdown menu list element (ul).
- fieldkeyof T | '_default'
-
- The field to search.
- fieldLabelstring
-
- The label to display.
- valuestring`
-
- Query string to match.
Contributions are welcome! Feel free to open an issue or submit a pull request.
Before submitting a pull request, please make sure to test your changes and update the documentation if necessary.
This project is licensed under the MIT License