useSearch React hook
easily search through an array with this hook.
— views
The hook
easily search through an array with this hook. With great TypeScript support.
src/hooks/useSearch.ts
import * as React from "react";
export function useSearch<T = object>(key: keyof T, items: T[]) {
const [search, setSearch] = React.useState("");
const [filtered, setFiltered] = React.useState<T[]>(items);
// if the 'items' change, make sure we update our state.
React.useEffect(() => {
setFiltered(items);
}, [items]);
function onChange(e: React.ChangeEvent<HTMLInputElement>) {
const value = e.target.value;
setSearch(value);
// if there's no hits found, set filtered back to all items
if (value.length <= 0) {
setFiltered(items);
// else, search on the provided 'key'
} else {
setFiltered(
items.filter((v) =>
(v[key] as unknown as string).toString().toLowerCase().includes(value.toLowerCase()),
),
);
}
}
return {
search,
onChange,
filtered,
};
}
tsx
Example
npm/yarn
You can now also use this hook via npm/yarn by installing my npm package:
npm install @casper124578/useful
bash
Later in your project
import { useSearch } from "@casper124578/useful/hooks/useSearch";
tsx