> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/algolia/docsearch/llms.txt
> Use this file to discover all available pages before exploring further.

# React Installation

> Install and configure DocSearch in React applications

DocSearch provides a native React component that integrates seamlessly with React applications. The component is built with React hooks and supports React 16.8+.

## Installation

Install the `@docsearch/react` package using your preferred package manager:

<CodeGroup>
  ```bash npm theme={null}
  npm install @docsearch/react
  ```

  ```bash yarn theme={null}
  yarn add @docsearch/react
  ```

  ```bash pnpm theme={null}
  pnpm add @docsearch/react
  ```
</CodeGroup>

<Note>
  The package requires React >= 16.8.0 and React DOM >= 16.8.0 as peer dependencies.
</Note>

### CDN Installation

For quick prototyping, you can load DocSearch from a CDN:

```html theme={null}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@docsearch/css@4" />
<script src="https://cdn.jsdelivr.net/npm/@docsearch/react@4"></script>
```

## Basic Setup

<Steps>
  <Step title="Import the DocSearch component">
    Import the `DocSearch` component and CSS styles:

    ```jsx theme={null}
    import { DocSearch } from '@docsearch/react';
    import '@docsearch/css';
    ```
  </Step>

  <Step title="Add DocSearch to your component">
    Render the `DocSearch` component with your Algolia credentials:

    ```jsx theme={null}
    function App() {
      return (
        <DocSearch
          appId="YOUR_APP_ID"
          apiKey="YOUR_SEARCH_API_KEY"
          indexName="YOUR_INDEX_NAME"
        />
      );
    }
    ```
  </Step>
</Steps>

<Note>
  Don't have your Algolia credentials yet? [Apply to DocSearch](https://docsearch.algolia.com/apply) to get started for free.
</Note>

## Complete Example

Here's a complete example with typical configuration:

```jsx App.jsx theme={null}
import React from 'react';
import { DocSearch } from '@docsearch/react';
import '@docsearch/css';

function App() {
  return (
    <div className="App">
      <header>
        <nav>
          <div className="logo">My Docs</div>
          <DocSearch
            appId="YOUR_APP_ID"
            apiKey="YOUR_SEARCH_API_KEY"
            indexName="YOUR_INDEX_NAME"
            placeholder="Search documentation"
          />
        </nav>
      </header>
      <main>
        {/* Your content */}
      </main>
    </div>
  );
}

export default App;
```

## API Reference

### DocSearch Component

The main React component for rendering DocSearch.

#### Props

<ParamField path="appId" type="string" required>
  Your Algolia application ID.
</ParamField>

<ParamField path="apiKey" type="string" required>
  Your Algolia Search API key (public, search-only key).
</ParamField>

<ParamField path="indexName" type="string">
  The name of your Algolia index to search.

  <Warning>
    The `indexName` prop is deprecated. Use the `indices` prop instead for multi-index support.
  </Warning>
</ParamField>

<ParamField path="indices" type="Array<DocSearchIndex | string>">
  List of indices to search. Each item can be a string (index name) or an object with `name` and optional `searchParameters`.

  ```jsx theme={null}
  <DocSearch
    appId="YOUR_APP_ID"
    apiKey="YOUR_SEARCH_API_KEY"
    indices={[
      { name: 'docs_v1', searchParameters: { facetFilters: ['version:1.0'] } },
      { name: 'docs_v2', searchParameters: { facetFilters: ['version:2.0'] } },
      'blog'
    ]}
  />
  ```
</ParamField>

<ParamField path="placeholder" type="string">
  Placeholder text for the search input. Defaults to "Search docs".
</ParamField>

<ParamField path="searchParameters" type="SearchParamsObject">
  Additional Algolia search parameters to apply to all queries.

  <Warning>
    The `searchParameters` prop is deprecated. Use the `indices` prop with per-index parameters instead.
  </Warning>
</ParamField>

<ParamField path="maxResultsPerGroup" type="number">
  Maximum number of results to show per category. Defaults to 5.
</ParamField>

<ParamField path="transformItems" type="(items: DocSearchHit[]) => DocSearchHit[]">
  Hook to transform search results before rendering.

  ```jsx theme={null}
  <DocSearch
    appId="YOUR_APP_ID"
    apiKey="YOUR_SEARCH_API_KEY"
    indexName="YOUR_INDEX_NAME"
    transformItems={(items) => {
      return items.map(item => ({
        ...item,
        url: item.url.replace('https://example.com', '')
      }));
    }}
  />
  ```
</ParamField>

<ParamField path="hitComponent" type="React.Component">
  Custom component to render individual search results.

  ```jsx theme={null}
  <DocSearch
    appId="YOUR_APP_ID"
    apiKey="YOUR_SEARCH_API_KEY"
    indexName="YOUR_INDEX_NAME"
    hitComponent={({ hit, children }) => (
      <a href={hit.url} className="custom-hit">
        {children}
      </a>
    )}
  />
  ```
</ParamField>

<ParamField path="resultsFooterComponent" type="React.Component">
  Custom component rendered at the bottom of the results panel.

  ```jsx theme={null}
  <DocSearch
    appId="YOUR_APP_ID"
    apiKey="YOUR_SEARCH_API_KEY"
    indexName="YOUR_INDEX_NAME"
    resultsFooterComponent={({ state }) => (
      <div className="results-footer">
        Found {state.collections.length} results
      </div>
    )}
  />
  ```
</ParamField>

<ParamField path="transformSearchClient" type="(searchClient: DocSearchTransformClient) => DocSearchTransformClient">
  Hook to wrap or modify the Algolia search client.

  ```jsx theme={null}
  <DocSearch
    appId="YOUR_APP_ID"
    apiKey="YOUR_SEARCH_API_KEY"
    indexName="YOUR_INDEX_NAME"
    transformSearchClient={(searchClient) => {
      searchClient.addAlgoliaAgent('my-app', '1.0.0');
      return searchClient;
    }}
  />
  ```
</ParamField>

<ParamField path="navigator" type="object">
  Custom navigator for controlling link navigation. Useful for client-side routing.

  ```jsx theme={null}
  // React Router example
  import { useNavigate } from 'react-router-dom';

  function SearchComponent() {
    const navigate = useNavigate();
    
    return (
      <DocSearch
        appId="YOUR_APP_ID"
        apiKey="YOUR_SEARCH_API_KEY"
        indexName="YOUR_INDEX_NAME"
        navigator={{
          navigate({ itemUrl }) {
            navigate(itemUrl);
          }
        }}
      />
    );
  }
  ```
</ParamField>

<ParamField path="disableUserPersonalization" type="boolean">
  Disable storage and display of recent and favorite searches. Defaults to `false`.
</ParamField>

<ParamField path="initialQuery" type="string">
  Query string to prefill when opening the search modal.
</ParamField>

<ParamField path="translations" type="DocSearchTranslations">
  Localized strings for the button and modal UI.

  ```jsx theme={null}
  <DocSearch
    appId="YOUR_APP_ID"
    apiKey="YOUR_SEARCH_API_KEY"
    indexName="YOUR_INDEX_NAME"
    translations={{
      button: {
        buttonText: 'Buscar',
        buttonAriaLabel: 'Buscar documentación'
      },
      modal: {
        searchBox: {
          resetButtonTitle: 'Borrar búsqueda',
          cancelButtonText: 'Cancelar'
        }
      }
    }}
  />
  ```
</ParamField>

<ParamField path="getMissingResultsUrl" type="({ query: string }) => string">
  Returns a URL to report missing results for a given query.

  ```jsx theme={null}
  <DocSearch
    appId="YOUR_APP_ID"
    apiKey="YOUR_SEARCH_API_KEY"
    indexName="YOUR_INDEX_NAME"
    getMissingResultsUrl={({ query }) => 
      `https://github.com/myorg/docs/issues/new?title=Missing results for "${query}"`
    }
  />
  ```
</ParamField>

<ParamField path="insights" type="object">
  Algolia Insights client integration for analytics.

  ```jsx theme={null}
  import aa from 'search-insights';

  aa('init', {
    appId: 'YOUR_APP_ID',
    apiKey: 'YOUR_SEARCH_API_KEY'
  });

  <DocSearch
    appId="YOUR_APP_ID"
    apiKey="YOUR_SEARCH_API_KEY"
    indexName="YOUR_INDEX_NAME"
    insights={true}
  />
  ```
</ParamField>

<ParamField path="theme" type="DocSearchTheme">
  Theme overrides for customizing the appearance.

  ```jsx theme={null}
  <DocSearch
    appId="YOUR_APP_ID"
    apiKey="YOUR_SEARCH_API_KEY"
    indexName="YOUR_INDEX_NAME"
    theme={{
      primaryColor: '#5468ff',
      backgroundColor: '#f5f6f7',
      textColor: '#1c1e21'
    }}
  />
  ```
</ParamField>

<ParamField path="portalContainer" type="DocumentFragment | Element">
  The container element where the modal should be portaled. Defaults to `document.body`.
</ParamField>

<ParamField path="keyboardShortcuts" type="DocSearchModalShortcuts">
  Configuration for keyboard shortcuts. Allows enabling/disabling specific shortcuts.

  ```jsx theme={null}
  <DocSearch
    appId="YOUR_APP_ID"
    apiKey="YOUR_SEARCH_API_KEY"
    indexName="YOUR_INDEX_NAME"
    keyboardShortcuts={{
      'Ctrl/Cmd+K': true,
      '/': false  // Disable forward slash shortcut
    }}
  />
  ```
</ParamField>

<ParamField path="askAi" type="DocSearchAskAi | string">
  Configuration for Ask AI mode. Pass an assistant ID string or a full configuration object.

  ```jsx theme={null}
  <DocSearch
    appId="YOUR_APP_ID"
    apiKey="YOUR_SEARCH_API_KEY"
    indexName="YOUR_INDEX_NAME"
    askAi={{
      assistantId: 'YOUR_ASSISTANT_ID',
      suggestedQuestions: true,
      searchParameters: {
        facetFilters: ['version:2.0']
      }
    }}
  />
  ```
</ParamField>

## Using Refs

You can access DocSearch methods using a ref:

```jsx theme={null}
import React, { useRef } from 'react';
import { DocSearch } from '@docsearch/react';
import '@docsearch/css';

function App() {
  const searchRef = useRef(null);
  
  const openSearch = () => {
    searchRef.current?.open();
  };
  
  const openAskAi = () => {
    searchRef.current?.openAskAi({ query: 'How do I get started?' });
  };
  
  return (
    <div>
      <button onClick={openSearch}>Open Search</button>
      <button onClick={openAskAi}>Ask AI</button>
      
      <DocSearch
        ref={searchRef}
        appId="YOUR_APP_ID"
        apiKey="YOUR_SEARCH_API_KEY"
        indexName="YOUR_INDEX_NAME"
      />
    </div>
  );
}
```

### Ref Methods

<ResponseField name="open" type="() => void">
  Opens the search modal programmatically.
</ResponseField>

<ResponseField name="close" type="() => void">
  Closes the search modal programmatically.
</ResponseField>

<ResponseField name="openAskAi" type="(initialMessage?: InitialAskAiMessage) => void">
  Opens Ask AI mode with an optional pre-filled message.

  ```jsx theme={null}
  searchRef.current?.openAskAi({ 
    query: 'How do I configure search?',
    messageId: 'msg_123' 
  });
  ```
</ResponseField>

<ResponseField name="isOpen" type="boolean">
  Returns `true` if the modal is currently open.
</ResponseField>

## Modular Components

DocSearch also exports individual components for advanced use cases:

### DocSearchButton

The search button component without the modal:

```jsx theme={null}
import { DocSearchButton } from '@docsearch/react/button';

function CustomSearch() {
  return (
    <DocSearchButton
      translations={{
        buttonText: 'Search docs',
        buttonAriaLabel: 'Search documentation'
      }}
      onClick={() => {
        console.log('Search button clicked');
      }}
    />
  );
}
```

### DocSearchModal

The search modal component without the button:

```jsx theme={null}
import { useState } from 'react';
import { DocSearchModal } from '@docsearch/react/modal';
import '@docsearch/react/style';

function CustomSearch() {
  const [isOpen, setIsOpen] = useState(false);
  
  return (
    <>
      <button onClick={() => setIsOpen(true)}>Search</button>
      
      {isOpen && (
        <DocSearchModal
          appId="YOUR_APP_ID"
          apiKey="YOUR_SEARCH_API_KEY"
          indexName="YOUR_INDEX_NAME"
          initialScrollY={window.scrollY}
          onClose={() => setIsOpen(false)}
        />
      )}
    </>
  );
}
```

### useDocSearchKeyboardEvents

Hook for handling keyboard shortcuts:

```jsx theme={null}
import { useRef, useState } from 'react';
import { useDocSearchKeyboardEvents } from '@docsearch/react/useDocSearchKeyboardEvents';

function CustomSearch() {
  const [isOpen, setIsOpen] = useState(false);
  const buttonRef = useRef(null);
  
  useDocSearchKeyboardEvents({
    isOpen,
    onOpen: () => setIsOpen(true),
    onClose: () => setIsOpen(false),
    searchButtonRef: buttonRef
  });
  
  return (
    <button ref={buttonRef} onClick={() => setIsOpen(true)}>
      Search
    </button>
  );
}
```

## TypeScript Support

DocSearch is written in TypeScript and includes full type definitions:

```tsx theme={null}
import type { DocSearchProps, DocSearchHit } from '@docsearch/react';
import { DocSearch } from '@docsearch/react';
import '@docsearch/css';

const searchConfig: DocSearchProps = {
  appId: 'YOUR_APP_ID',
  apiKey: 'YOUR_SEARCH_API_KEY',
  indexName: 'YOUR_INDEX_NAME',
  transformItems: (items: DocSearchHit[]) => {
    return items.map(item => ({
      ...item,
      url: new URL(item.url, window.location.origin).href
    }));
  }
};

function App() {
  return <DocSearch {...searchConfig} />;
}
```

## Styling

DocSearch comes with default styles. You can customize the appearance using:

### CSS Variables

```css theme={null}
:root {
  --docsearch-primary-color: #5468ff;
  --docsearch-text-color: #1c1e21;
  --docsearch-spacing: 12px;
  --docsearch-icon-stroke-width: 1.4;
  --docsearch-highlight-color: var(--docsearch-primary-color);
  --docsearch-muted-color: #969faf;
  --docsearch-container-background: rgba(101, 108, 133, 0.8);
  --docsearch-modal-background: #f5f6f7;
}
```

### Theme Prop

```jsx theme={null}
<DocSearch
  appId="YOUR_APP_ID"
  apiKey="YOUR_SEARCH_API_KEY"
  indexName="YOUR_INDEX_NAME"
  theme={{
    primaryColor: '#5468ff',
    backgroundColor: '#ffffff',
    textColor: '#1c1e21',
    spacing: 12
  }}
/>
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Configuration" icon="gear" href="/api/configuration">
    Learn about all available configuration options
  </Card>

  <Card title="Styling" icon="palette" href="/concepts/styling">
    Customize the appearance of your search
  </Card>

  <Card title="Ask AI" icon="sparkles" href="/concepts/ask-ai">
    Enable AI-powered search assistance
  </Card>

  <Card title="API Reference" icon="code" href="/api/docsearch-react">
    Explore the complete API documentation
  </Card>
</CardGroup>
