Last active
July 5, 2022 16:56
-
-
Save makvoid/0540e2e471fe263fa83f433371eef112 to your computer and use it in GitHub Desktop.
App.js example using InstantSearch React hooks with useHits
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import algoliasearch from 'algoliasearch/lite'; | |
import { | |
Configure, | |
Highlight, | |
Hits, | |
useHits, // Add import here | |
Index, | |
InstantSearch, | |
SearchBox, | |
Pagination, | |
} from 'react-instantsearch-hooks-web'; | |
import 'instantsearch.css/themes/algolia.css'; | |
import './App.css'; | |
const searchClient = algoliasearch( | |
'latency', | |
'6be0576ff61c053d5f9a3225e2a90f76' | |
); | |
function App() { | |
return ( | |
<div className="container"> | |
<InstantSearch indexName="instant_search" searchClient={searchClient}> | |
<SearchBox /> | |
<Index indexName="instant_search"> | |
<h2> | |
index: <code>instant_search</code> | |
<HitCount /> | |
</h2> | |
<Configure hitsPerPage={16} /> | |
<Hits hitComponent={ProductHit} /> | |
<Pagination /> | |
</Index> | |
<Index indexName="instant_search_demo_query_suggestions"> | |
<h2> | |
index: <code>instant_search_demo_query_suggestions</code> | |
<HitCount /> | |
</h2> | |
<Configure hitsPerPage={8} /> | |
<Hits hitComponent={QuerySuggestionHit} /> | |
</Index> | |
</InstantSearch> | |
</div> | |
); | |
} | |
// Add a new component or modify an existing | |
// one that is a child element of an Index | |
// which will allow us to access the underlying | |
// information for each index | |
function HitCount(props) { | |
const hits = useHits() | |
// SearchResults can be obtained from hits.results (index name, count, total pages, etc) | |
console.log(hits.results.index, hits) | |
return ( | |
<span className="hitsCount">(Showing {hits.hits.length} / {hits.results.nbHits})</span> | |
) | |
} | |
function ProductHit({ hit }) { | |
return ( | |
<div> | |
<Highlight attribute="name" hit={hit} /> | |
</div> | |
); | |
} | |
function QuerySuggestionHit({ hit }) { | |
return ( | |
<div> | |
<Highlight attribute="query" hit={hit} /> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment