Unverified Commit 2c811af2 authored by Dhaya's avatar Dhaya Committed by GitHub

examples: Upgrade `with-algolia-react-instantsearch` example to latest major…

examples: Upgrade `with-algolia-react-instantsearch` example to latest major version and use app router (#59961)
Co-authored-by: 's avatarLee Robinson <me@leerob.io>
parent bc41a7f8
# With Algolia React InstantSearch example # With Algolia React InstantSearch example
The goal of this example is to illustrate how you can use [Algolia React InstantSearch](https://community.algolia.com/react-instantsearch/) to perform your search in an application developed with Next.js. It also illustrates how you can keep in sync the Url with the search. The goal of this example is to illustrate how you can use [Algolia React InstantSearch](https://www.algolia.com/doc/guides/building-search-ui/what-is-instantsearch/react/) to perform your search in an application developed with Next.js. It also illustrates how you can keep in sync the Url with the search.
## Deploy your own
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/vercel/next.js/tree/canary/examples/with-algolia-react-instantsearch&project-name=with-algolia-react-instantsearch&repository-name=with-algolia-react-instantsearch)
## How to use ## How to use
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example: Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), [pnpm](https://pnpm.io), or [Bun](https://bun.sh/docs/cli/bunx) to bootstrap the example:
```bash ```bash
npx create-next-app --example with-algolia-react-instantsearch with-algolia-react-instantsearch-app npx create-next-app --example with-algolia-react-instantsearch with-algolia-react-instantsearch-app
...@@ -18,9 +24,14 @@ yarn create next-app --example with-algolia-react-instantsearch with-algolia-rea ...@@ -18,9 +24,14 @@ yarn create next-app --example with-algolia-react-instantsearch with-algolia-rea
pnpm create next-app --example with-algolia-react-instantsearch with-algolia-react-instantsearch-app pnpm create next-app --example with-algolia-react-instantsearch with-algolia-react-instantsearch-app
``` ```
To set up Algolia: ```bash
bun create next-app --example with-algolia-react-instantsearch with-algolia-react-instantsearch-app
```
This example is already configured with an e-commerce index, but you can easily customize it by:
- create an [algolia](https://www.algolia.com/) account or use this already [configured index](https://community.algolia.com/react-instantsearch/Getting_started.html#before-we-start) - [creating an Algolia account](https://www.algolia.com/doc/guides/getting-started/quick-start/#sign-up-for-an-algolia-account),
- update the `appId`, `apikey` and `indexName` you want to search on in [`components/instantsearch.js`](components/instantsearch.js) - [indexing your data](https://www.algolia.com/doc/guides/sending-and-managing-data/send-and-update-your-data/#index-your-data-without-coding),
- and updating the `APP_ID`, `API_KEY` and `INDEX_NAME` you want to search on in [`components/Search.tsx`](components/Search.tsx)
Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)). Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
import React from 'react'
import '../styles/global.css'
import 'instantsearch.css/themes/satellite-min.css'
export const metadata = {
title: 'Next.js with Algolia React InstantSearch',
description: 'Generated by Next.js',
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
import React from 'react'
import Search from '../components/Search'
export const dynamic = 'force-dynamic'
export default function Page() {
return <Search />
}
import React from 'react'
export function Panel({
children,
header,
footer,
}: {
children: React.ReactNode
header?: React.ReactNode
footer?: React.ReactNode
}) {
return (
<div className="ais-Panel">
{header && <div className="ais-Panel-header">{header}</div>}
<div className="ais-Panel-body">{children}</div>
{footer && <div className="ais-Panel-footer">{footer}</div>}
</div>
)
}
'use client'
import algoliasearch from 'algoliasearch/lite'
import type { Hit as AlgoliaHit } from 'instantsearch.js'
import React from 'react'
import { import {
RefinementList,
SearchBox,
Hits,
Configure, Configure,
Highlight, Highlight,
Hits,
Pagination, Pagination,
InstantSearch, RefinementList,
} from 'react-instantsearch-dom' SearchBox,
import type { InstantSearchProps } from 'react-instantsearch-dom' } from 'react-instantsearch'
import { InstantSearchNext } from 'react-instantsearch-nextjs'
import { Panel } from './Panel'
const HitComponent = ({ hit }: any) => ( type HitProps = {
<div className="hit"> hit: AlgoliaHit<{
<div> name: string
<div className="hit-picture"> description: string
<img src={`${hit.image}`} /> price: number
</div> }>
</div> }
<div className="hit-content">
<div> const APP_ID = 'latency'
<Highlight attribute="name" hit={hit} /> const API_KEY = '6be0576ff61c053d5f9a3225e2a90f76'
<span> - ${hit.price}</span> const INDEX_NAME = 'instant_search'
<span> - {hit.rating} stars</span>
</div> const searchClient = algoliasearch(APP_ID, API_KEY)
<div className="hit-type">
<Highlight attribute="type" hit={hit} /> function Hit({ hit }: HitProps) {
</div> return (
<div className="hit-description"> <>
<Highlight attribute="description" hit={hit} /> <Highlight hit={hit} attribute="name" className="Hit-label" />
</div> <span className="Hit-price">${hit.price}</span>
</div> </>
</div> )
) }
export function Search(props: InstantSearchProps) { export default function Search() {
return ( return (
<InstantSearch {...props}> <InstantSearchNext
searchClient={searchClient}
indexName={INDEX_NAME}
routing
future={{
preserveSharedStateOnUnmount: true,
}}
>
<Configure hitsPerPage={12} /> <Configure hitsPerPage={12} />
<header>
<h1>React InstantSearch + Next.js</h1>
<SearchBox />
</header>
<main> <main>
<div className="menu"> <div>
<RefinementList attribute="categories" /> <Panel header="Brands">
<RefinementList attribute="brand" showMore />
</Panel>
</div> </div>
<div className="results"> <div>
<Hits hitComponent={HitComponent} /> <SearchBox />
<Hits hitComponent={Hit} />
<Pagination />
</div> </div>
</main> </main>
<footer> </InstantSearchNext>
<Pagination />
</footer>
</InstantSearch>
) )
} }
...@@ -6,21 +6,18 @@ ...@@ -6,21 +6,18 @@
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"algoliasearch": "^4.14.2", "algoliasearch": "^4.22.0",
"instantsearch.css": "^7.4.5", "instantsearch.css": "^8.1.0",
"instantsearch.js": "^4.63.0",
"next": "latest", "next": "latest",
"qs": "^6.11.0",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"react-instantsearch-dom": "^6.38.0" "react-instantsearch": "^7.5.0",
"react-instantsearch-nextjs": "^0.1.7"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^18.11.9", "@types/react": "^18.2.45",
"@types/qs": "^6.9.7", "@types/react-dom": "^18.2.18",
"@types/react": "^18.0.25", "typescript": "^5.3.3"
"@types/react-dom": "^18.0.8",
"@types/react-instantsearch-core": "^6.26.2",
"@types/react-instantsearch-dom": "^6.12.3",
"typescript": "^4.8.4"
} }
} }
import type { AppProps } from 'next/app'
import 'instantsearch.css/themes/algolia.css'
import '../styles/global.css'
export default function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}
import type { InferGetServerSidePropsType, GetServerSideProps } from 'next'
import type { SearchState } from 'react-instantsearch-core'
import { useState, useEffect, useRef } from 'react'
import { useRouter } from 'next/router'
import algoliasearch from 'algoliasearch/lite'
import { findResultsState } from 'react-instantsearch-dom/server'
import { Search } from '../components/Search'
import { createURL, searchStateToURL, pathToSearchState } from '../utils'
// Demo key provided by https://github.com/algolia/react-instantsearch
const searchClient = algoliasearch(
'latency',
'6be0576ff61c053d5f9a3225e2a90f76'
)
const defaultProps = {
searchClient,
indexName: 'instant_search',
}
export default function Page({
resultsState,
searchState: initialState,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
const router = useRouter()
const debouncedSetState = useRef()
const [searchState, setSearchState] = useState(initialState)
const onSearchStateChange = (state: SearchState) => {
clearTimeout(debouncedSetState.current)
;(debouncedSetState as any).current = setTimeout(() => {
const href = searchStateToURL(state)
router.push(href, href, { shallow: true })
}, 700)
setSearchState(state)
}
useEffect(() => {
if (router) {
router.beforePopState((state: SearchState) => {
const { url } = state
setSearchState(pathToSearchState(url))
return true
})
}
}, [router])
return (
<Search
{...defaultProps}
searchState={searchState}
resultsState={resultsState}
onSearchStateChange={onSearchStateChange}
createURL={createURL}
/>
)
}
interface PageProps {
searchState: SearchState
resultsState: unknown
}
export const getServerSideProps: GetServerSideProps<PageProps> = async ({
resolvedUrl,
}) => {
const searchState = pathToSearchState(resolvedUrl)
const resultsState = await findResultsState(Search, {
...defaultProps,
searchState,
})
// Pre-serialize `findResultsState` object return so Next.js' serialization checks pass
// https://github.com/vercel/next.js/issues/11993
return {
props: {
resultsState: JSON.parse(JSON.stringify(resultsState)),
searchState,
},
}
}
This diff is collapsed.
html { html,
font-family: sans-serif; body {
padding: 0;
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
} }
header { body {
display: flex; padding: 0.5rem;
flex-direction: column;
align-items: center;
}
main {
display: flex;
margin: 25px 0;
} }
.menu { * {
flex: 2; box-sizing: border-box;
} }
footer { main {
text-align: center; display: grid;
align-items: flex-start;
grid-template-columns: minmax(min-content, 200px) 1fr;
gap: 0.5rem;
} }
.ais-Hits,
.ais-Pagination { .ais-Pagination {
margin-bottom: 25px; margin-top: 1rem;
}
.results {
flex: 9;
} }
.hit { .ais-Hits-item {
display: flex; display: flex;
align-items: center; justify-content: space-between;
}
.hit-actions {
display: flex;
}
.hit-content {
padding: 0px 10px;
}
.hit-picture img {
width: 80px;
height: 80px;
} }
.hit-type { .Hit-price {
color: #888888; color: #888888;
font-size: 13px;
} }
...@@ -13,8 +13,13 @@ ...@@ -13,8 +13,13 @@
"resolveJsonModule": true, "resolveJsonModule": true,
"isolatedModules": true, "isolatedModules": true,
"jsx": "preserve", "jsx": "preserve",
"incremental": true "incremental": true,
"plugins": [
{
"name": "next"
}
]
}, },
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"] "exclude": ["node_modules"]
} }
import type { SearchState } from 'react-instantsearch-core'
import qs from 'qs'
export const createURL = (state: SearchState) => `?${qs.stringify(state)}`
export const pathToSearchState = (path: string) =>
path.includes('?') ? qs.parse(path.substring(path.indexOf('?') + 1)) : {}
export const searchStateToURL = (searchState: SearchState) =>
searchState ? `${window.location.pathname}?${qs.stringify(searchState)}` : ''
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment