@digigov/text-search
v1.2.0-rc.21
Published
@digigov text-search
Downloads
288
Keywords
Readme
@digigov/text-search
@digigov/text-search
is a library that provides text search functionality in the form of a React hook. It allows searching through a list of objects by creating an index of the objects' properties. It uses flexsearch under the hood.
The objects in the list can have any structure, but an identifier property must be provided. The hook will use the id
property (if present) or it will create an id
property for each object, using the index of the object in the list.
Alternatively, you may specify which property to use as an identifier by passing it in the idKey
of the hook's options. Obviously, the identifier property must be unique for each object.
Installation
npm install @digigov/text-search
or
yarn add @digigov/text-search
Usage
Here is a basic example of how to use the hook:
import React from 'react';
import useSearch from '@digigov/text-search';
const documents = [
{ name: 'John', address: '123 Main St' },
{ name: 'Jane', address: '456 Main St' },
{ name: 'Jack', address: '789 Main St' },
{ name: 'Jill', address: '101 Main St' },
];
const MyComponent = () => {
const [searchTerm, setSearchTerm] = React.useState('');
const { data, loading, search, reset } = useSearch(documents, searchTerm);
const handleReset = () => {
setSearchTerm('');
reset();
};
return (
<div>
<input
type="text"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
placeholder="Enter search term"
/>
<button onClick={search}>Search</button>
<button onClick={handleReset}>Reset</button>
{loading && <p>Loading...</p>}
<ul>
{data.map((item) => (
<li key={item.name}>
<p>{item.name}</p>
<p>{item.address}</p>
</li>
))}
</ul>
</div>
);
};
export default MyComponent;