Setting Up Algolia Search in Next.js
Guide through the process of adding Algolia search functionality to a Next.js app, including search bar component and search result display.
import algoliasearch from 'algoliasearch/lite';
import { InstantSearch, SearchBox, Hits } from 'react-instantsearch-dom';
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyApiKey');
function Hit({ hit }) {
return (
<div>
<h2>{hit.name}</h2>
<p>{hit.description}</p>
</div>
);
}
function Search() {
return (
<InstantSearch indexName='your_index_name' searchClient={searchClient}>
<SearchBox />
<Hits hitComponent={Hit} />
</InstantSearch>
);
}
export default Search;
This code snippet imports the Algolia search client and components from 'react-instantsearch-dom'. It initializes the client with your Algolia application ID and search-only API key. The 'Hit' component is defined for rendering individual search results. The 'Search' component sets up the search interface, including a search box and a container for displaying hits by using Algolia's InstantSearch component with the defined hits.