Files
saladeaula.digital/superpage/src/pages/_components/Search.jsx
2025-04-25 17:12:35 -03:00

63 lines
1.5 KiB
JavaScript

import { useState } from "react";
import Fuse from "fuse.js";
// https://fusejs.io/api/options.html
const options = {
keys: ["data.title", "data.slug"],
includeMatches: true,
minMatchCharLength: 2,
threshold: 0.5,
};
export default function Search({ searchlist }) {
const [query, setQuery] = useState("");
const fuse = new Fuse(searchlist, options);
// Set a limit to the items: 5
const items = fuse
.search(query)
.map((result) => result.item)
.slice(0, 5);
const onChange = (e) => {
setQuery(e.target.value);
};
return (
<>
<input
id="search"
type="text"
className="focus:outline-none w-full pr-5 py-3.5 rounded-r-xl"
value={query}
autoComplete="false"
onChange={onChange}
/>
{query.length > 1 && (
<div className="absolute w-full top-full bg-white mt-1.5 p-5 rounded-xl drop-shadow space-y-2.5">
<p>
Encontrado {items.length} resultado(s) para '
<strong>{query}</strong>'
</p>
{items.length > 0 && (
<ul className="list-disc list-inside">
{items.map(({ data }, idx) => (
<li key={idx}>
<a
href={`/${data.slug}`}
className="font-medium hover:underline"
>
{data.title}
</a>
</li>
))}
</ul>
)}
</div>
)}
</>
);
}