### Install Dependencies and Start Development Server
Source: https://github.com/algolia/react-instantsearch/blob/master/CONTRIBUTING.md
Installs project dependencies using Yarn and starts the development server, typically for using Storybook. Make sure you have Yarn installed.
```sh
yarn
yarn start
```
--------------------------------
### Install Dependencies and Start Next.js Example using yarn
Source: https://github.com/algolia/react-instantsearch/blob/master/examples/next/README.md
These commands show how to install project dependencies without a lockfile and then start the Next.js development server for the React InstantSearch example. This is typically done after cloning the example project.
```sh
yarn install --no-lockfile
yarn run dev
```
--------------------------------
### Install and Start React Native Example (Yarn)
Source: https://github.com/algolia/react-instantsearch/blob/master/examples/hooks-react-native/README.md
These Yarn commands are used to install project dependencies without using a lockfile and then start the React Native example application. This is typically run after cloning the example project.
```bash
yarn install --no-lockfile
yarn run start
```
--------------------------------
### Basic React InstantSearch Setup
Source: https://github.com/algolia/react-instantsearch/blob/master/packages/react-instantsearch-hooks-web/README.md
Demonstrates a basic setup for React InstantSearch Hooks Web. It initializes the `algoliasearch` client with credentials, then renders the `InstantSearch` component, wrapping `SearchBox` and `Hits` components. This provides a functional search interface with minimal code.
```javascript
import React from 'react';
import ReactDOM from 'react-dom';
import algoliasearch from 'algoliasearch/lite';
import { InstantSearch, SearchBox, Hits } from 'react-instantsearch-hooks-web';
const searchClient = algoliasearch(
'latency',
'6be0576ff61c053d5f9a3225e2a90f76'
);
const App = () => (
);
```
--------------------------------
### Clone Next.js SSR Example using curl
Source: https://github.com/algolia/react-instantsearch/blob/master/examples/next/README.md
This snippet demonstrates how to clone the Next.js server-side rendering example for React InstantSearch using curl and tar. It fetches the master branch and extracts the Next.js example directory.
```bash
curl https://codeload.github.com/algolia/react-instantsearch/tar.gz/master | tar -xz --strip=2 react-instantsearch-master/examples/next
```
--------------------------------
### Install React InstantSearch Hooks Web
Source: https://github.com/algolia/react-instantsearch/blob/master/packages/react-instantsearch-hooks-web/README.md
Installs the `react-instantsearch-hooks-web` library and its dependency `algoliasearch` using either yarn or npm package managers. This is the first step to integrating Algolia's search functionality into a React application.
```sh
yarn add algoliasearch react-instantsearch-hooks-web
# or
npm install algoliasearch react-instantsearch-hooks-web
```
--------------------------------
### Basic Search Setup with React InstantSearch
Source: https://context7.com/algolia/react-instantsearch/llms.txt
Demonstrates setting up a fundamental search interface using React InstantSearch. It includes importing necessary components, initializing the Algolia search client, defining a hit component for displaying search results, and rendering the InstantSearch wrapper with a SearchBox and Hits component.
```jsx
import React from 'react';
import algoliasearch from 'algoliasearch/lite';
import { InstantSearch, SearchBox, Hits, Highlight } from 'react-instantsearch-hooks-web';
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
function Hit({ hit }) {
return (
{hit.description}
);
}
export default function App() {
return (
);
}
```
--------------------------------
### Clone React InstantSearch Hooks Example (Shell)
Source: https://github.com/algolia/react-instantsearch/blob/master/examples/hooks-react-native/README.md
This command-line snippet clones the React InstantSearch Hooks example for React Native from GitHub. It uses `curl` to download the master tarball and `tar` to extract the specific example directory, stripping unnecessary parent folders.
```sh
curl https://codeload.github.com/algolia/react-instantsearch/tar.gz/master | tar -xz --strip=2 react-instantsearch-master/examples/hooks-react-native
```
--------------------------------
### Manage Active Filters with CurrentRefinements and ClearRefinements in React
Source: https://context7.com/algolia/react-instantsearch/llms.txt
This example demonstrates how to display and manage active search filters using the `CurrentRefinements` and `ClearRefinements` components in React InstantSearch. It allows users to see applied filters, transform their labels, and clear them all at once. This setup requires defining `RefinementList` components for filtering attributes.
```jsx
import React from 'react';
import {
InstantSearch,
SearchBox,
Hits,
RefinementList,
CurrentRefinements,
ClearRefinements,
} from 'react-instantsearch-hooks-web';
import algoliasearch from 'algoliasearch/lite';
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
export default function App() {
return (
);
}
```
--------------------------------
### Migrating InstantSearch to searchClient Prop
Source: https://github.com/algolia/react-instantsearch/blob/master/MIGRATION.md
Demonstrates the change in `InstantSearch` component usage in React InstantSearch v6.x.x, replacing `appId` and `apiKey` with the `searchClient` prop. This change simplifies configuration and allows for custom clients.
```javascript
import React from "react";
import algoliasearch from "algoliasearch/lite";
import { InstantSearch, SearchBox } from "react-instantsearch-dom";
const searchClient = algoliasearch(
"latency",
"6be0576ff61c053d5f9a3225e2a90f76"
);
const App = () => (
);
```
--------------------------------
### React InstantSearch App Component Update for SSR
Source: https://github.com/algolia/react-instantsearch/blob/master/MIGRATION.md
Shows the updated `App.js` component for React InstantSearch v6.x.x, adapting to the new SSR pattern. It demonstrates receiving `indexName`, `searchClient`, and `resultsState` as props for `InstantSearch`.
```javascript
import React from "react";
import { InstantSearch, SearchBox } from "react-instantsearch-dom";
const App = ({ indexName, searchClient, resultsState }) => (
);
export { App };
```
--------------------------------
### SSR Client-Side Hydration in React InstantSearch
Source: https://github.com/algolia/react-instantsearch/blob/master/MIGRATION.md
Illustrates client-side hydration for server-side rendered React InstantSearch applications in v6.x.x. It shows how to pass `indexName` and `searchClient` from the server state to the client for seamless rendering.
```javascript
import React from 'react';
import { hydrate } from 'react-dom';
import { App } from './App';
const indexName = "instant_search";
const searchClient = algoliasearch(
"latency",
"6be0576ff61c053d5f9a3225e2a90f76"
);
hydrate(
,
document.getElementById("root")
);
```
--------------------------------
### React Custom Hit Display with useHits Hook
Source: https://context7.com/algolia/react-instantsearch/llms.txt
This example demonstrates creating a custom display for search results using the `useHits` hook from `react-instantsearch-hooks`. It allows for transforming the hit items before rendering, such as calculating a discounted price. Dependencies include `react` and `react-instantsearch-hooks`. It takes props for hit configuration and outputs a list of articles representing search results.
```jsx
import React from 'react';
import { InstantSearch, SearchBox, useHits } from 'react-instantsearch-hooks';
import algoliasearch from 'algoliasearch/lite';
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
function CustomHits(props) {
const { hits, sendEvent } = useHits({
...props,
escapeHTML: false,
transformItems: (items) =>
items.map((item) => ({
...item,
discountedPrice: item.price * 0.9,
})),
});
function handleClick(hit) {
sendEvent('click', hit, 'Hit Clicked');
}
return (
{hits.map((hit) => (
handleClick(hit)}>
{hit.name}
Original: ${hit.price}
Discounted: ${hit.discountedPrice.toFixed(2)}
))}
);
}
export default function App() {
return (
);
}
```
--------------------------------
### SSR Server-Side Changes in React InstantSearch
Source: https://github.com/algolia/react-instantsearch/blob/master/MIGRATION.md
Demonstrates modifications to the server-side rendering logic in React InstantSearch v6.x.x. It shows how to use the `findResultsState` function with `indexName` and `searchClient` for server-side data fetching and hydration.
```javascript
import React from 'react';
import { renderToString } from "react-dom/server";
import { findResultsState } from "react-instantsearch-dom/server";
import { App } from "./App";
const indexName = "instant_search";
const searchClient = algoliasearch(
"latency",
"6be0576ff61c053d5f9a3225e2a90f76"
);
server.get("/", async (req, res) => {
const initialState = {
resultsState: await findResultsState(App, {
indexName,
searchClient
})
};
const plainHTML = renderToString();
// ...
});
```
--------------------------------
### Implement Sort Controls with useSortBy Hook in React
Source: https://context7.com/algolia/react-instantsearch/llms.txt
This snippet demonstrates how to implement sorting controls for search results using the `useSortBy` hook from React InstantSearch. It allows users to reorder results based on different criteria like relevance, price, or name. This requires Algolia search client setup and defining sortable indexes.
```jsx
import React from 'react';
import { InstantSearch, SearchBox, Hits, useSortBy } from 'react-instantsearch-hooks';
import algoliasearch from 'algoliasearch/lite';
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
function SortBySelect(props) {
const { currentRefinement, options, refine, canRefine } = useSortBy({
...props,
items: [
{ label: 'Relevance', value: 'products' },
{ label: 'Price (asc)', value: 'products_price_asc' },
{ label: 'Price (desc)', value: 'products_price_desc' },
{ label: 'Name (A-Z)', value: 'products_name_asc' },
],
});
if (!canRefine) {
return null;
}
return (
);
}
export default function App() {
return (
);
}
```
--------------------------------
### Remove root prop in InstantSearch (React)
Source: https://github.com/algolia/react-instantsearch/blob/master/MIGRATION.md
This change removes the `root` prop from `InstantSearch` and `Index` components. The functionality can now be achieved by wrapping the `InstantSearch` component with the desired element. This simplifies the component structure and improves compatibility, especially for React Native users.
```diff
// ...
const App = () => (
+
+
);
```
--------------------------------
### Deploy Preview Documentation
Source: https://github.com/algolia/react-instantsearch/blob/master/CONTRIBUTING.md
Deploys a preview version of the project's documentation, often used for review before merging to production. This process utilizes Netlify for deployment.
```sh
yarn docs:deploy-preview
```
--------------------------------
### Deploy Production Documentation
Source: https://github.com/algolia/react-instantsearch/blob/master/CONTRIBUTING.md
Deploys the project's documentation to the production environment. This command typically automates the process of building and publishing documentation.
```sh
yarn docs:deploy-production
```
--------------------------------
### Pagination and Configuration with React InstantSearch
Source: https://context7.com/algolia/react-instantsearch/llms.txt
Shows how to implement pagination and configure search parameters using InstantSearch components. This includes using the Configure component for settings like hitsPerPage and attributesToSnippet, and integrating Pagination, HitsPerPage, and Stats components for a complete search experience.
```jsx
import React from 'react';
import {
InstantSearch,
SearchBox,
Hits,
Pagination,
Configure,
HitsPerPage,
Stats
} from 'react-instantsearch-hooks-web';
import algoliasearch from 'algoliasearch/lite';
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
export default function App() {
return (
);
}
```
--------------------------------
### Release Project to npm
Source: https://github.com/algolia/react-instantsearch/blob/master/CONTRIBUTING.md
Initiates the release process for the project, which involves creating a pull request for the next version. A GITHUB_TOKEN environment variable with a personal access token is required. After review and merging, CircleCI handles the npm publication.
```sh
yarn release
```
--------------------------------
### Run Unit Tests with Jest
Source: https://github.com/algolia/react-instantsearch/blob/master/CONTRIBUTING.md
Executes the unit tests for the project using Jest. This command performs a single run of all tests. Ensure Jest is configured within the project's dependencies.
```sh
yarn test
```
--------------------------------
### Server-Side Rendering with React InstantSearch
Source: https://context7.com/algolia/react-instantsearch/llms.txt
Implements server-side rendering (SSR) for React InstantSearch to enhance initial page load performance. It utilizes `getServerState` for fetching initial data on the server and `renderToString` to render the React components. Dependencies include 'react', 'react-dom/server', and 'react-instantsearch-hooks-server'.
```jsx
// server.js
import express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { getServerState } from 'react-instantsearch-hooks-server';
import App from './App';
const app = express();
app.get('/', async (req, res) => {
const location = new URL(`${req.protocol}://${req.get('host')}${req.originalUrl}`);
const serverState = await getServerState(, {
renderToString,
});
const html = renderToString(
);
res.send(`
SSR Search
${html}
`);
});
app.listen(3000);
// App.js
import React from 'react';
import {
InstantSearch,
InstantSearchSSRProvider,
SearchBox,
Hits,
RefinementList,
Configure,
} from 'react-instantsearch-hooks-web';
import algoliasearch from 'algoliasearch/lite';
import { history } from 'instantsearch.js/es/lib/routers';
import { simple } from 'instantsearch.js/es/lib/stateMappings';
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
export default function App({ serverState, location }) {
return (
);
}
```
--------------------------------
### Lint Project Code
Source: https://github.com/algolia/react-instantsearch/blob/master/CONTRIBUTING.md
Lints the project's codebase to ensure code quality and consistency. This command typically uses ESLint and Prettier for formatting.
```sh
yarn lint
```
--------------------------------
### URL Routing with InstantSearch in React
Source: https://context7.com/algolia/react-instantsearch/llms.txt
Explains how to synchronize the search state with URL parameters for persistent search experiences and shareable search results. This is achieved by configuring the `routing` prop of `InstantSearch` with a router (e.g., `history`) and a state mapping (e.g., `simple`). This allows users to bookmark or share specific search queries.
```jsx
import React from 'react';
import { InstantSearch, SearchBox, Hits, RefinementList } from 'react-instantsearch-hooks-web';
import algoliasearch from 'algoliasearch/lite';
import { history } from 'instantsearch.js/es/lib/routers';
import { simple } from 'instantsearch.js/es/lib/stateMappings';
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
export default function App() {
return (
);
}
```
--------------------------------
### React Custom Search Box with useSearchBox Hook
Source: https://context7.com/algolia/react-instantsearch/llms.txt
This snippet shows how to build a custom search box component using the `useSearchBox` hook from `react-instantsearch-hooks`. It allows full control over the UI and search interactions, including input handling, submission, and resetting the search query. Dependencies include `react` and `react-instantsearch-hooks`. It takes props for configuration and outputs a search input and buttons.
```jsx
import React, { useRef, useState } from 'react';
import { InstantSearch, useSearchBox, Hits } from 'react-instantsearch-hooks';
import algoliasearch from 'algoliasearch/lite';
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
function CustomSearchBox(props) {
const { query, refine, isSearchStalled } = useSearchBox(props);
const [inputValue, setInputValue] = useState(query);
const inputRef = useRef(null);
function handleSubmit(event) {
event.preventDefault();
refine(inputValue);
}
function handleReset() {
setInputValue('');
refine('');
inputRef.current?.focus();
}
return (
);
}
export default function App() {
return (
);
}
```
--------------------------------
### Dynamic Search Parameters with useConfigure Hook
Source: https://context7.com/algolia/react-instantsearch/llms.txt
Demonstrates how to dynamically set search parameters, such as 'hitsPerPage', 'attributesToSnippet', 'filters', and 'distinct', using the `useConfigure` hook in React InstantSearch. This allows for real-time updates to search behavior based on user interactions. Dependencies include 'react' and 'react-instantsearch-hooks'.
```jsx
import React, { useState } from 'react';
import { InstantSearch, SearchBox, Hits, useConfigure } from 'react-instantsearch-hooks';
import algoliasearch from 'algoliasearch/lite';
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
function SearchSettings() {
const [hitsPerPage, setHitsPerPage] = useState(10);
const [sortBy, setSortBy] = useState('products_price_asc');
useConfigure({
hitsPerPage,
attributesToSnippet: ['description:30'],
snippetEllipsisText: '…',
filters: 'available:true',
distinct: true,
});
return (
);
}
export default function App() {
return (
);
}
```
--------------------------------
### Multi-Index Search with Index Component in React
Source: https://context7.com/algolia/react-instantsearch/llms.txt
Shows how to perform searches across multiple Algolia indices simultaneously using the `Index` component. This pattern is useful for applications that need to display results from different data sources (e.g., products and articles) in a single interface. It utilizes `Configure` to set index-specific search parameters.
```jsx
import React from 'react';
import {
InstantSearch,
SearchBox,
Hits,
Index,
Highlight,
Configure,
} from 'react-instantsearch-hooks-web';
import algoliasearch from 'algoliasearch/lite';
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
function ProductHit({ hit }) {
return ;
}
function ArticleHit({ hit }) {
return ;
}
export default function App() {
return (
Products
Articles
Blog Posts
);
}
```
--------------------------------
### Enable Watch Mode for Application Reloads
Source: https://github.com/algolia/react-instantsearch/blob/master/CONTRIBUTING.md
Enables watch mode for the development server, allowing applications to automatically reload on code changes. This command should be run in a separate terminal tab from the main development server.
```sh
yarn watch
```
--------------------------------
### Single-Select Menu Filters with useMenu Hook
Source: https://context7.com/algolia/react-instantsearch/llms.txt
Shows how to create interactive single-select menu filters (e.g., category filters) using the `useMenu` hook in React InstantSearch. This hook provides data for menu items, allows refinement of search results, and indicates whether refinement is possible. Dependencies include 'react' and 'react-instantsearch-hooks'.
```jsx
import React from 'react';
import { InstantSearch, SearchBox, Hits, useMenu } from 'react-instantsearch-hooks';
import algoliasearch from 'algoliasearch/lite';
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
function CategoryMenu(props) {
const { items, refine, canRefine } = useMenu({
...props,
limit: 10,
sortBy: ['name:asc'],
});
if (!canRefine) {
return null;
}
return (
);
}
export default function App() {
return (
);
}
```
--------------------------------
### React Custom Refinement List with useRefinementList Hook
Source: https://context7.com/algolia/react-instantsearch/llms.txt
This snippet illustrates building a custom faceted filter component using the `useRefinementList` hook from `react-instantsearch-hooks`. It provides full UI customization for filtering based on an attribute, including displaying counts, managing 'show more' functionality, and sorting. Dependencies include `react` and `react-instantsearch-hooks`. It takes an `attribute` prop and outputs a list of filterable items.
```jsx
import React from 'react';
import { InstantSearch, SearchBox, Hits, useRefinementList } from 'react-instantsearch-hooks';
import algoliasearch from 'algoliasearch/lite';
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
function CustomRefinementList(props) {
const {
items,
refine,
canRefine,
isShowingMore,
canToggleShowMore,
toggleShowMore,
} = useRefinementList({
...props,
limit: 5,
showMore: true,
showMoreLimit: 15,
sortBy: ['count:desc', 'name:asc'],
});
if (!canRefine) {
return
No filters available
;
}
return (
Filter by {props.attribute}
{items.map((item) => (
))}
{canToggleShowMore && (
)}
);
}
export default function App() {
return (
);
}
```
--------------------------------
### Custom Pagination with usePagination Hook in React
Source: https://context7.com/algolia/react-instantsearch/llms.txt
Demonstrates how to create custom pagination controls using the `usePagination` hook. This hook provides state and methods to manage page navigation, including checking if it's the first or last page and refining the current page. It's useful for building bespoke pagination UI elements.
```jsx
import React from 'react';
import { InstantSearch, SearchBox, Hits, usePagination } from 'react-instantsearch-hooks';
import algoliasearch from 'algoliasearch/lite';
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
function CustomPagination(props) {
const {
currentRefinement,
nbPages,
refine,
isFirstPage,
isLastPage,
canRefine,
} = usePagination(props);
if (!canRefine) {
return null;
}
return (
);
}
export default function App() {
return (
);
}
```
--------------------------------
### Run Unit Tests in Watch Mode
Source: https://github.com/algolia/react-instantsearch/blob/master/CONTRIBUTING.md
Runs unit tests continuously in watch mode, automatically re-running tests when code changes are detected. This is useful for iterative testing during development.
```sh
yarn test:watch
```
--------------------------------
### Refinement List with Search in React InstantSearch
Source: https://context7.com/algolia/react-instantsearch/llms.txt
Illustrates how to add faceted filters to a search interface using the RefinementList component. This snippet shows how to enable search within refinement lists for attributes like 'brand' and apply multiple refinement lists for different attributes, alongside a SearchBox and Hits.
```jsx
import React from 'react';
import { InstantSearch, RefinementList, SearchBox, Hits } from 'react-instantsearch-hooks-web';
import algoliasearch from 'algoliasearch/lite';
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
export default function App() {
return (
);
}
```
--------------------------------
### Display Highlighted Search Terms with Highlight Component in React
Source: https://context7.com/algolia/react-instantsearch/llms.txt
This snippet shows how to use the `Highlight` component from React InstantSearch to visually indicate which parts of the search results match the user's query. It supports custom tag names for highlighted and non-highlighted text, enhancing result readability. Requires Algolia search client and indexed data.
```jsx
import React from 'react';
import { InstantSearch, SearchBox, Hits, Highlight } from 'react-instantsearch-hooks-web';
import algoliasearch from 'algoliasearch/lite';
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
function ProductHit({ hit }) {
return (
Brand:
);
}
export default function App() {
return (
);
}
```
--------------------------------
### Infinite Scroll Results with useInfiniteHits Hook in React
Source: https://context7.com/algolia/react-instantsearch/llms.txt
Implements infinite scrolling for search results using the `useInfiniteHits` hook. This hook allows fetching more results on demand, typically by a 'Load more' button, and managing the state of the infinite scroll. It's suitable for displaying large datasets without overwhelming the user.
```jsx
import React from 'react';
import { InstantSearch, SearchBox, useInfiniteHits } from 'react-instantsearch-hooks';
import algoliasearch from 'algoliasearch/lite';
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
function InfiniteHitsList(props) {
const { hits, isLastPage, showMore } = useInfiniteHits({
...props,
escapeHTML: false,
cache: true,
});
return (
{hits.map((hit) => (
{hit.name}
{hit.description}
))}
{!isLastPage && (
)}
);
}
export default function App() {
return (
);
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.