|
| 1 | +import { useState, useMemo } from "react"; |
| 2 | +import algoliasearch from "algoliasearch/lite"; |
| 3 | +import { createAutocomplete } from "@algolia/autocomplete-core"; |
| 4 | +import { getAlgoliaResults } from "@algolia/autocomplete-preset-algolia"; |
| 5 | + |
| 6 | +export default function ({ title }) { |
| 7 | + const searchClient = algoliasearch( |
| 8 | + "latency", |
| 9 | + "6be0576ff61c053d5f9a3225e2a90f76" |
| 10 | + ); |
| 11 | + |
| 12 | + // (1) Create a React state. |
| 13 | + const [autocompleteState, setAutocompleteState] = useState({}); |
| 14 | + const autocomplete = useMemo( |
| 15 | + () => |
| 16 | + createAutocomplete({ |
| 17 | + onStateChange({ state }) { |
| 18 | + // (2) Synchronize the Autocomplete state with the React state. |
| 19 | + setAutocompleteState(state); |
| 20 | + }, |
| 21 | + id: 'Search thing', |
| 22 | + getSources() { |
| 23 | + return [ |
| 24 | + // (3) Use an Algolia index source. |
| 25 | + { |
| 26 | + sourceId: "products", |
| 27 | + getItemInputValue({ item }) { |
| 28 | + return item.query; |
| 29 | + }, |
| 30 | + getItems({ query }) { |
| 31 | + return getAlgoliaResults({ |
| 32 | + searchClient, |
| 33 | + queries: [ |
| 34 | + { |
| 35 | + indexName: "instant_search", |
| 36 | + query, |
| 37 | + params: { |
| 38 | + hitsPerPage: 4, |
| 39 | + highlightPreTag: "<mark>", |
| 40 | + highlightPostTag: "</mark>", |
| 41 | + }, |
| 42 | + }, |
| 43 | + ], |
| 44 | + }); |
| 45 | + }, |
| 46 | + getItemUrl({ item }) { |
| 47 | + return item.url; |
| 48 | + }, |
| 49 | + }, |
| 50 | + ]; |
| 51 | + }, |
| 52 | + }), |
| 53 | + [] |
| 54 | + ); |
| 55 | + |
| 56 | + return ( |
| 57 | + <div> |
| 58 | + <h1>{title}</h1> |
| 59 | + <div className="aa-Autocomplete" {...autocomplete.getRootProps({})}> |
| 60 | + <input className="aa-Input" {...autocomplete.getInputProps({})} /> |
| 61 | + <div className="aa-Panel" {...autocomplete.getPanelProps({})}> |
| 62 | + {autocompleteState.isOpen && |
| 63 | + autocompleteState.collections.map((collection, index) => { |
| 64 | + const { source, items } = collection; |
| 65 | + return ( |
| 66 | + <div key={`source-${index}`} className="aa-Source"> |
| 67 | + {items.length > 0 && ( |
| 68 | + <ul className="aa-List" {...autocomplete.getListProps()}> |
| 69 | + {items.map((item) => ( |
| 70 | + <li |
| 71 | + key={item.objectID} |
| 72 | + className="aa-Item" |
| 73 | + {...autocomplete.getItemProps({ |
| 74 | + item, |
| 75 | + source, |
| 76 | + })} |
| 77 | + > |
| 78 | + {item.name} |
| 79 | + </li> |
| 80 | + ))} |
| 81 | + </ul> |
| 82 | + )} |
| 83 | + </div> |
| 84 | + ); |
| 85 | + })} |
| 86 | + </div> |
| 87 | + </div> |
| 88 | + </div> |
| 89 | + ); |
| 90 | +} |
0 commit comments