Unverified Commit 994089fc authored by Max Proske's avatar Max Proske Committed by GitHub

Improve `with-algolia-react-instantsearch` example and convert to TypeScript (#42617)

Converted to TypeScript to match Contribution docs, and updated/simplified the example.

- Replaced stylesheets in Head component with imported styles
- Removed `style-loader`, `css-loader`, `cross-env`, `prop-types` packages
- Removed custom webpack config

## Documentation / Examples

- [X] Make sure the linting passes by running `pnpm build && pnpm lint`
- [X] The "examples guidelines" are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent 081b8fba
import React from 'react'
import PropTypes from 'prop-types'
import { import {
RefinementList, RefinementList,
SearchBox, SearchBox,
...@@ -9,9 +7,9 @@ import { ...@@ -9,9 +7,9 @@ import {
Pagination, Pagination,
InstantSearch, InstantSearch,
} from 'react-instantsearch-dom' } from 'react-instantsearch-dom'
import { indexName, searchClient } from './instantsearch' import type { InstantSearchProps } from 'react-instantsearch-dom'
const HitComponent = ({ hit }) => ( const HitComponent = ({ hit }: any) => (
<div className="hit"> <div className="hit">
<div> <div>
<div className="hit-picture"> <div className="hit-picture">
...@@ -34,48 +32,25 @@ const HitComponent = ({ hit }) => ( ...@@ -34,48 +32,25 @@ const HitComponent = ({ hit }) => (
</div> </div>
) )
HitComponent.propTypes = { export function Search(props: InstantSearchProps) {
hit: PropTypes.object,
}
export default class App extends React.Component {
static propTypes = {
searchState: PropTypes.object,
resultsState: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
onSearchStateChange: PropTypes.func,
}
render() {
return ( return (
<InstantSearch <InstantSearch {...props}>
indexName={indexName} <Configure hitsPerPage={12} />
searchClient={searchClient}
resultsState={this.props.resultsState}
onSearchStateChange={this.props.onSearchStateChange}
searchState={this.props.searchState}
>
<Configure hitsPerPage={10} />
<header> <header>
<h1>React InstantSearch + Next.Js</h1> <h1>React InstantSearch + Next.js</h1>
<SearchBox /> <SearchBox />
</header> </header>
<content> <main>
<menu> <div className="menu">
<RefinementList attribute="category" /> <RefinementList attribute="categories" />
</menu> </div>
<div className="results">
<Hits hitComponent={HitComponent} /> <Hits hitComponent={HitComponent} />
</content> </div>
</main>
<footer> <footer>
<Pagination /> <Pagination />
<div>
See{' '}
<a href="https://github.com/algolia/react-instantsearch/tree/master/packages/react-instantsearch/examples/next-app">
source code
</a>{' '}
on github
</div>
</footer> </footer>
</InstantSearch> </InstantSearch>
) )
}
} }
import NextHead from 'next/head'
import { string } from 'prop-types'
import React from 'react'
const defaultDescription = ''
const defaultOGURL = ''
const defaultOGImage = ''
export const Head = (props) => (
<NextHead>
<meta charSet="UTF-8" />
<title>{props.title || ''}</title>
<meta
name="description"
content={props.description || defaultDescription}
/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" sizes="192x192" href="/static/touch-icon.png" />
<link rel="apple-touch-icon" href="/static/touch-icon.png" />
<link rel="mask-icon" href="/static/favicon-mask.svg" color="#49B882" />
<meta property="og:url" content={props.url || defaultOGURL} />
<meta property="og:title" content={props.title || ''} />
<meta
property="og:description"
content={props.description || defaultDescription}
/>
<meta name="twitter:site" content={props.url || defaultOGURL} />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:image" content={props.ogImage || defaultOGImage} />
<meta property="og:image" content={props.ogImage || defaultOGImage} />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<link
rel="stylesheet"
href="https://unpkg.com/react-instantsearch-theme-algolia@3.0.0/style.min.css"
/>
<link rel="stylesheet" href="../static/instantsearch.css" />
</NextHead>
)
Head.propTypes = {
title: string,
description: string,
url: string,
ogImage: string,
}
export default Head
export * from './head'
export { default as App } from './app'
export { findResultsState } from './instantsearch'
import { findResultsState } from 'react-instantsearch-dom/server'
import algoliasearch from 'algoliasearch/lite'
const indexName = 'instant_search'
// Keys are supplied from Algolia's instant search example
// https://github.com/algolia/react-instantsearch
const searchClient = algoliasearch(
'latency',
'6be0576ff61c053d5f9a3225e2a90f76'
)
export { findResultsState, indexName, searchClient }
module.exports = {
webpack: (config) => {
// Fixes npm packages that depend on `fs` module
config.node = {
fs: 'empty',
}
config.module.rules.push({
test: /\.css$/,
loader: ['style-loader', 'css-loader'],
})
if (config.resolve.alias) {
delete config.resolve.alias.react
delete config.resolve.alias['react-dom']
}
return config
},
}
...@@ -2,19 +2,25 @@ ...@@ -2,19 +2,25 @@
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "next", "dev": "next",
"build": "cross-env NODE_ENV=development next build", "build": "next build",
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"algoliasearch": "4.3.0", "algoliasearch": "^4.14.2",
"cross-env": "^7.0.2", "instantsearch.css": "^7.4.5",
"css-loader": "1.0.0",
"next": "latest", "next": "latest",
"prop-types": "^15.5.10", "qs": "^6.11.0",
"qs": "^6.4.0",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"react-instantsearch-dom": "6.6.0", "react-instantsearch-dom": "^6.38.0"
"style-loader": "^0.17.0" },
"devDependencies": {
"@types/node": "^18.11.9",
"@types/qs": "^6.9.7",
"@types/react": "^18.0.25",
"@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 { Head, App } from '../components'
import {
findResultsState,
indexName,
searchClient,
} from '../components/instantsearch'
import { Component } from 'react'
import Router from 'next/router'
import qs from 'qs'
const updateAfter = 700
const searchStateToUrl = (searchState) =>
searchState ? `${window.location.pathname}?${qs.stringify(searchState)}` : ''
export default class Home extends Component {
constructor(props) {
super(props)
this.onSearchStateChange = this.onSearchStateChange.bind(this)
}
onSearchStateChange = (searchState) => {
clearTimeout(this.debouncedSetState)
this.debouncedSetState = setTimeout(() => {
const href = searchStateToUrl(searchState)
Router.push(href, href, {
shallow: true,
})
}, updateAfter)
this.setState({ searchState })
}
async componentDidMount() {
this.setState({
searchState: qs.parse(window.location.search.slice(1)),
resultsState: await findResultsState(App, { indexName, searchClient }),
})
}
UNSAFE_componentWillReceiveProps() {
this.setState({ searchState: qs.parse(window.location.search.slice(1)) })
}
render() {
return (
<div>
<Head title="Home" />
<div>
{this.state && this.state.resultsState && this.state.searchState && (
<App
resultsState={this.state.resultsState}
onSearchStateChange={this.onSearchStateChange}
searchState={this.state.searchState}
/>
)}
</div>
</div>
)
}
}
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,
},
}
}
.ais-InstantSearch__root { html {
align-items: center; font-family: sans-serif;
} }
header { header {
...@@ -8,11 +8,12 @@ header { ...@@ -8,11 +8,12 @@ header {
align-items: center; align-items: center;
} }
content { main {
display: flex; display: flex;
margin: 25px 0;
} }
menu { .menu {
flex: 2; flex: 2;
} }
...@@ -20,8 +21,12 @@ footer { ...@@ -20,8 +21,12 @@ footer {
text-align: center; text-align: center;
} }
results { .ais-Pagination {
flex: 10; margin-bottom: 25px;
}
.results {
flex: 9;
} }
.hit { .hit {
......
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"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