### Install react-bootstrap-typeahead using npm or yarn Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/README.md Instructions for installing the react-bootstrap-typeahead package using either npm or yarn. This is the first step to integrating the typeahead component into your React project. ```bash npm install --save react-bootstrap-typeahead ``` ```bash yarn add react-bootstrap-typeahead ``` -------------------------------- ### Asynchronous Typeahead for Search Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md Provides an example of using the AsyncTypeahead component for performing searches with debounced user input and asynchronous data fetching. It demonstrates setting loading states, defining the search callback, and updating the component's options based on API responses. ```jsx `${option.login}`} onSearch={(query) => { this.setState({isLoading: true}); fetch(`https://api.github.com/search/users?q=${query}`) .then(resp => resp.json()) .then(json => this.setState({ isLoading: false, options: json.items, })); }} options={this.state.options} /> ``` -------------------------------- ### Custom Input Rendering with Typeahead Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md Demonstrates how to provide a custom input element for the Typeahead component. This allows for advanced input customization, including integration with other UI components like FloatingLabel. The example shows how to correctly pass refs to the input element for proper component functionality. ```jsx ( { inputRef(node); referenceElementRef(node); }} type="text" /> )} /> ``` -------------------------------- ### Migrate `hintContainer` HOC to `Hint` Component Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/Upgrading.md The `hintContainer` Higher-Order Component (HOC) has been replaced by a `Hint` component. This change simplifies usage and better reflects the component's relationship with the input. The examples show the transition from v4.x to v5.0. ```jsx import { Form } from 'react-bootstrap'; import { Typeahead, hintContainer } from 'react-bootstrap-typeahead'; const FormControlWithHint = hintContainer(Form.Control); ( )} /> ``` ```jsx import { Form } from 'react-bootstrap'; import { Typeahead, Hint } from 'react-bootstrap-typeahead'; ( )} /> ``` -------------------------------- ### Handle `AsyncTypeahead` `onSearch` Re-instantiation (v5) Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/Upgrading.md Addresses potential issues with `AsyncTypeahead`'s `onSearch` handler in v5 due to its rewrite with hooks. If `onSearch` is re-instantiated on each render, it can cancel the debounced function. The examples show how to bind the handler in the constructor, use class properties, or employ `useCallback` with a dependency array to prevent this. ```jsx // This may cause problems: { // Do stuff... }} /> ``` ```jsx // Instead, do one of the following: class MyComponent extends React.Component { render () { } handleSearch = (query) => { // Do stuff... } } ``` ```jsx const MyComponent = () => { const handleSearch = useCallback((query) => { // Do stuff... }, []); return ( ); }; ``` -------------------------------- ### Import Typeahead Component (JSX) Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/Upgrading.md Demonstrates how to import the Typeahead component from 'react-bootstrap-typeahead' in both ES2015 and CommonJS module systems, comparing v0.10.x and v1.x. ```jsx // v0.10.x import Typeahead from 'react-bootstrap-typeahead'; // ES2015 var Typeahead = require('react-bootstrap-typeahead').default; // CommonJS // v1.x import {Typeahead} from 'react-bootstrap-typeahead'; // ES2015 var Typeahead = require('react-bootstrap-typeahead').Typeahead; // CommonJS ``` -------------------------------- ### Control Menu Visibility with `renderMenu` for No Results Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/Upgrading.md The behavior where a falsy `emptyLabel` would hide the menu has been removed. To achieve this, you should now use the `renderMenu` prop to return `null` when there are no results, providing explicit control over menu visibility. ```jsx { if (!results.length) { return null; } return ; }} /> ``` -------------------------------- ### Implement Pagination for Large Datasets in React Typeahead Source: https://context7.com/ericgio/react-bootstrap-typeahead/llms.txt Handle large datasets efficiently in react-bootstrap-typeahead by implementing built-in pagination support. This example shows how to load more results as the user scrolls or interacts with the pagination controls. It requires the `Typeahead` component and an `onPaginate` handler. ```jsx import { Typeahead } from 'react-bootstrap-typeahead'; function PaginationExample() { const [selected, setSelected] = useState([]); const [currentPage, setCurrentPage] = useState(1); // Generate large dataset const allOptions = Array.from({ length: 1000 }, (_, i) => ({ id: i + 1, label: `Item ${i + 1}`, description: `Description for item ${i + 1}` })); const handlePaginate = (e, shownResults) => { setCurrentPage(currentPage + 1); console.log(`Loading more results. Currently showing: ${shownResults}`); }; return ( ); } ``` -------------------------------- ### Programmatic Control of Typeahead with Ref in React Source: https://context7.com/ericgio/react-bootstrap-typeahead/llms.txt Access and control react-bootstrap-typeahead methods programmatically using refs. This example demonstrates how to focus, blur, clear the selection, and toggle the menu of the typeahead input. It requires the `useRef` hook and the `Typeahead` component. ```jsx import { useRef } from 'react'; import { Typeahead } from 'react-bootstrap-typeahead'; function RefMethodsExample() { const typeaheadRef = useRef(null); const [selected, setSelected] = useState([]); const options = ['Option 1', 'Option 2', 'Option 3', 'Option 4']; return (
); } ``` -------------------------------- ### Update renderMenuItemChildren Callback Signature (JSX) Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/Upgrading.md Illustrates the change in the argument order for the `renderMenuItemChildren` callback function between v0.10.x and v1.x of react-bootstrap-typeahead. The data item is now the first argument. ```jsx // v0.10.x renderMenuItemChildren(props, result, index) { // Rendering code here... } // v1.x renderMenuItemChildren(result, props, index) { // Rendering code here... } ``` -------------------------------- ### Customize Dropdown Menu Rendering in React Source: https://context7.com/ericgio/react-bootstrap-typeahead/llms.txt Customize the dropdown menu for react-bootstrap-typeahead to include grouping, sections, and custom styling. This example demonstrates how to group options by category and apply specific styles to menu items. It requires the `Typeahead`, `Menu`, and `MenuItem` components. ```jsx import { Typeahead, Menu, MenuItem } from 'react-bootstrap-typeahead'; function CustomMenuExample() { const [selected, setSelected] = useState([]); const options = [ { name: 'Apple', category: 'Fruit', color: 'red' }, { name: 'Banana', category: 'Fruit', color: 'yellow' }, { name: 'Carrot', category: 'Vegetable', color: 'orange' }, { name: 'Broccoli', category: 'Vegetable', color: 'green' } ]; return ( { const grouped = results.reduce((acc, option) => { const category = option.category; if (!acc[category]) acc[category] = []; acc[category].push(option); return acc; }, {}); return ( {Object.entries(grouped).map(([category, items]) => (
{category}
{items.map((item, index) => ( {item.name} ))}
))}
); }} /> ); } ``` -------------------------------- ### Customize Token Rendering in React Bootstrap Typeahead Source: https://context7.com/ericgio/react-bootstrap-typeahead/llms.txt Customize the appearance and behavior of tokens when using react-bootstrap-typeahead in multi-select mode. This example shows how to render custom tokens with avatars and role information. It utilizes the `Typeahead` and `Token` components. ```jsx import { Typeahead, Token } from 'react-bootstrap-typeahead'; function CustomTokenExample() { const [selected, setSelected] = useState([]); const users = [ { id: 1, name: 'John Doe', role: 'Admin', avatar: '👤' }, { id: 2, name: 'Jane Smith', role: 'Editor', avatar: '👥' }, { id: 3, name: 'Bob Johnson', role: 'Viewer', avatar: '👨' } ]; return ( ( {option.avatar} {option.name} ({option.role}) )} /> ); } ``` -------------------------------- ### AsyncTypeahead Initialization Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md Illustrates how the AsyncTypeahead component can be created by wrapping the base Typeahead component with the `withAsync` higher-order component. This provides a programmatic way to enable asynchronous search capabilities. ```jsx import { Typeahead, withAsync } from 'react-bootstrap-typeahead'; const AsyncTypeahead = withAsync(Typeahead); ``` -------------------------------- ### Hint Component Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md The `` component provides a hint or suggestion to the user. ```APIDOC ## ### Description Component that provides a hint or suggestion to the user. ### Method N/A (Component) ### Endpoint N/A (Component) ### Parameters #### Props (Specific props for `` would be listed here, but are not detailed in the provided text.) ### Request Example N/A (Component) ### Response N/A (Component) ``` -------------------------------- ### useHint Hook Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md A hook for managing hint functionality within the typeahead. ```APIDOC ## useHint ### Description A hook for managing hint functionality within the typeahead. ### Method N/A (Hook) ### Endpoint N/A (Hook) ### Parameters (Specific parameters for `useHint` would be listed here, but are not detailed in the provided text.) ### Request Example N/A (Hook) ### Response N/A (Hook) ``` -------------------------------- ### Explicitly Pass Refs to DOM Nodes with `renderInput` Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/Upgrading.md When using `renderInput`, you must now explicitly pass refs to both `inputRef` and `referenceElementRef` to a DOM node, typically the input element itself or a container. This addresses the removal of `findDOMNode` which was deprecated in React 16.3. ```jsx ( { inputRef(inputNode); referenceElementRef(inputNode); }} /> )} /> ``` -------------------------------- ### Custom Hint Component with `useHint` Hook Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md Shows how to implement a custom hint component for an input field using the `useHint` hook. This hook is particularly useful when you need to customize the markup for the hint. It provides `hintRef` for referencing the hint element and `hintText` for the actual hint content. ```jsx import { useHint } from 'react-bootstrap-typeahead'; const CustomHint = (props) => { const { hintRef, hintText } = useHint(props); return (
{props.children}
); }; ``` -------------------------------- ### Update `shouldSelectHint` to `selectHint` Prop (v5 to v6) Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/Upgrading.md Migrates from the `shouldSelectHint` prop within `inputProps` to the top-level `selectHint` prop in v6. This change simplifies hint selection logic. The function signature remains the same, accepting `shouldSelect` and `event` arguments. ```jsx ( event.key === "Enter" || shouldSelect; ) }} /> ``` ```jsx ( event.key === "Enter" || shouldSelect; )} /> ``` -------------------------------- ### Menu Component Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md The `` component renders the dropdown menu of options. ```APIDOC ## ### Description Component that renders the dropdown menu of options. ### Method N/A (Component) ### Endpoint N/A (Component) ### Parameters #### Props (Specific props for `` would be listed here, but are not detailed in the provided text.) ### Request Example N/A (Component) ### Response N/A (Component) ``` -------------------------------- ### useItem & withItem HOC Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md Connects individual menu items with the main typeahead component via context, abstracting complex functionality. ```APIDOC ## useItem & withItem ### Description Connects individual menu items with the main typeahead component via context and abstracts a lot of complex functionality required for behaviors like keying through the menu and input hinting. Also provides `onClick` behavior and active state. If you use your own menu item components (in `renderMenu` for example), you are strongly advised to use either the hook or the HOC: ```jsx import { MenuItem } from 'react-bootstrap'; import { Menu, Typeahead, useItem, withItem } from 'react-bootstrap-typeahead'; const Item = withItem(MenuItem); // OR const Item = (props) => ; ( {results.map((option, position) => ( {option.label} ))} )} /> ``` ### Method HOC / Hook ``` -------------------------------- ### useItem & withItem Hooks/HOCs Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md Hooks and higher-order components for managing individual item selection logic. ```APIDOC ## useItem & withItem ### Description Hooks and higher-order components for managing individual item selection logic. ### Method N/A (Hook/HOC) ### Endpoint N/A (Hook/HOC) ### Parameters (Specific parameters for `useItem` and `withItem` would be listed here, but are not detailed in the provided text.) ### Request Example N/A (Hook/HOC) ### Response N/A (Hook/HOC) ``` -------------------------------- ### Highlighter Component Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md The `` component is used for highlighting matching text within options. ```APIDOC ## ### Description Component used for highlighting matching text within options. ### Method N/A (Component) ### Endpoint N/A (Component) ### Parameters #### Props (Specific props for `` would be listed here, but are not detailed in the provided text.) ### Request Example N/A (Component) ### Response N/A (Component) ``` -------------------------------- ### Menu Component Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md Provides the markup for a Bootstrap menu with functionality for specifying a label when there are no results. ```APIDOC ## Menu Component ### Description Provides the markup for a Bootstrap menu, along with some extra functionality for specifying a label when there are no results. ### Props #### `emptyLabel` - **Type**: `node` - **Default**: `'No matches found.'` - **Description**: Message to display in the menu if there are no valid results. #### `id` - **Type**: `string | number` - **Required**: Yes - **Description**: Id value required for accessibility. #### `maxHeight` - **Type**: `string` - **Default**: `'300px'` - **Description**: Maximum height of the dropdown menu. ``` -------------------------------- ### Input Component Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md The `` component is a foundational input element for the typeahead. ```APIDOC ## ### Description Foundational input element for the typeahead. ### Method N/A (Component) ### Endpoint N/A (Component) ### Parameters #### Props (Specific props for `` would be listed here, but are not detailed in the provided text.) ### Request Example N/A (Component) ### Response N/A (Component) ``` -------------------------------- ### Pass `withToken` Ref to Custom Token DOM Node Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/Upgrading.md For custom tokens, the ref provided by `withToken` must now be explicitly passed to the token's root DOM node. This is a consequence of removing `findDOMNode` and ensuring proper ref handling in custom components. ```jsx const MyToken = withToken(forwardRef((props, ref) => (
{props.children}
))); ``` -------------------------------- ### Manually Pass Ref to Custom Menu Item DOM Node Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/Upgrading.md When using custom menu items, `tokenContainer` no longer implicitly handles refs. You must now manually forward the `ref` provided by `tokenContainer` to the underlying DOM node of your custom menu item component. ```jsx ( {option.label} )} /> ``` -------------------------------- ### useToken & withToken Hooks/HOCs Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md Hooks and higher-order components for managing token-based selections. ```APIDOC ## useToken & withToken ### Description Hooks and higher-order components for managing token-based selections. ### Method N/A (Hook/HOC) ### Endpoint N/A (Hook/HOC) ### Parameters (Specific parameters for `useToken` and `withToken` would be listed here, but are not detailed in the provided text.) ### Request Example N/A (Hook/HOC) ### Response N/A (Hook/HOC) ``` -------------------------------- ### Custom Token Component with `withToken` HOC Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md Demonstrates creating a custom token component using the `withToken` Higher-Order Component. This approach wraps a custom token component with the necessary behaviors for token interaction, such as click and blur events. The `withToken` HOC injects props like `active` and `onRemove` into the wrapped component. ```jsx import { withToken } from 'react-bootstrap-typeahead'; import { forwardRef } from 'react'; const MyToken = forwardRef(({ active, onRemove, ...props }, ref) => (
)); // HOC const CustomToken = withToken(MyToken); ``` -------------------------------- ### Custom Menu Item Rendering with Highlighter Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md Shows how to customize the rendering of individual menu items in the Typeahead component, using the Highlighter component to emphasize matching text. This snippet illustrates passing down props like `text` to the Highlighter for effective search term highlighting within each option. ```jsx ( {option[props.labelKey]} )} /> ``` -------------------------------- ### Custom Menu Rendering with Popper.js in React-Bootstrap-Typeahead Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/Upgrading.md React-Bootstrap-Typeahead now utilizes Popper.js for menu positioning, managed via `react-popper`. When implementing a custom menu component, ensure it correctly consumes the `innerRef` prop passed down by Popper.js and applies it to the `ref` of the underlying DOM element for proper functionality. ```jsx class MyCustomMenu extends React.Component { render() { // `innerRef` is passed down by the Popper... const {innerRef, ...props} = this.props; // ...and must be passed to the `ref` of your custom component. return
; } } ``` -------------------------------- ### useAsync & withAsync Hooks/HOCs Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md Hooks and higher-order components for managing asynchronous behavior in typeaheads. ```APIDOC ## useAsync & withAsync ### Description Hooks and higher-order components for managing asynchronous behavior in typeaheads. ### Method N/A (Hook/HOC) ### Endpoint N/A (Hook/HOC) ### Parameters (Specific parameters for `useAsync` and `withAsync` would be listed here, but are not detailed in the provided text.) ### Request Example N/A (Hook/HOC) ### Response N/A (Hook/HOC) ``` -------------------------------- ### TypeaheadInputSingle & TypeaheadInputMulti Components Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md Components for single and multi-selection typeahead inputs. ```APIDOC ## & ### Description Components for single and multi-selection typeahead inputs. ### Method N/A (Component) ### Endpoint N/A (Component) ### Parameters #### Props (Specific props for these components would be listed here, but are not detailed in the provided text.) ### Request Example N/A (Component) ### Response N/A (Component) ``` -------------------------------- ### Update filterBy Callback Signature in React-Bootstrap-Typeahead Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/Upgrading.md The `filterBy` callback in React-Bootstrap-Typeahead has been updated. In v2.0, it received the user-input `text` as the second parameter. In v3.0, it now receives a `props` object which includes `text` as `props.text`, along with other internal props. This change requires updating the callback signature to correctly access filtering-related data. ```jsx // v2.0 { // Your own filtering code goes here. }} /> ``` ```jsx // v3.0 { // Your own filtering code goes here. // `text` is now `props.text` }} /> ``` -------------------------------- ### Custom Token Component with `useToken` Hook Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md Illustrates creating a custom token component using the `useToken` hook. This hook provides the same functionality as the `withToken` HOC but allows for more direct integration within the token component itself. It exposes props such as `active`, `onRemove`, and `ref` to manage token behavior and state. ```jsx import { useToken } from 'react-bootstrap-typeahead'; const MyToken = (props) => { const { active, onRemove, ref, ...otherProps } = useToken(props); return (
); }; ``` -------------------------------- ### Update renderToken Callback Signature in React-Bootstrap-Typeahead Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/Upgrading.md The `renderToken` callback in React-Bootstrap-Typeahead has been modified. Previously (v2.0), it accepted the `option`, `onRemove` function, and `index`. In v3.0, the `onRemove` function is now nested within the `props` object, which is passed as the second argument instead of `onRemove` directly. This necessitates an update to how the `onRemove` function is accessed within the callback. ```jsx // v2.0 { // Your own token rendering code. }} /> ``` ```jsx // v3.0 { // Your own token rendering code. // `onRemove` is now `props.onRemove` }} /> ``` -------------------------------- ### MenuItem Component Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md Provides the markup for a Bootstrap menu item, wrapped by the `withItem` HOC for proper behavior within the typeahead context. ```APIDOC ## MenuItem Component ### Description Provides the markup for a Bootstrap menu item, but is wrapped by the [`withItem` HOC](#useitem--withitem) to ensure proper behavior within the typeahead context. Provided for use if a more customized `Menu` is desired. ### Props #### `option` - **Type**: `Object | string` - **Required**: Yes - **Description**: The data item to be displayed. #### `position` - **Type**: `number` - **Description**: The position of the item as rendered in the menu. Allows the top-level `Typeahead` component to be be aware of the item's position despite any custom ordering or grouping in `renderMenu`. **Note:** The value must be a unique, zero-based, sequential integer for proper behavior when keying through the menu. ``` -------------------------------- ### Customizing Menu Items with useItem and withItem HOCs Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md Demonstrates how to use the `useItem` hook or `withItem` Higher-Order Component (HOC) to enhance custom menu item components within the Typeahead. This is recommended when creating custom `renderMenu` implementations to ensure proper behavior, such as keying through the menu and input hinting. ```jsx import { MenuItem } from 'react-bootstrap'; import { Menu, Typeahead, useItem, withItem } from 'react-bootstrap-typeahead'; const Item = withItem(MenuItem); // OR const Item = (props) => ; ( {results.map((option, position) => ( {option.label} ))} )} /> ``` -------------------------------- ### AsyncTypeahead Component Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md The `` component is designed for typeahead inputs that fetch options asynchronously. ```APIDOC ## ### Description Component for typeahead inputs that fetch options asynchronously. ### Method N/A (Component) ### Endpoint N/A (Component) ### Parameters #### Props (Specific props for `` would be listed here, but are not detailed in the provided text.) ### Request Example N/A (Component) ### Response N/A (Component) ``` -------------------------------- ### MenuItem Component Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md The `` component renders an individual option within the menu. ```APIDOC ## ### Description Component that renders an individual option within the menu. ### Method N/A (Component) ### Endpoint N/A (Component) ### Parameters #### Props (Specific props for `` would be listed here, but are not detailed in the provided text.) ### Request Example N/A (Component) ### Response N/A (Component) ``` -------------------------------- ### Rendering Customization (labelKey) Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md Determines which key or function is used to render the display label for each option in the typeahead. It can be a string for a simple key or a function for complex label generation. See the Rendering section for more details. ```javascript labelKey="username" // Or with a custom function: labelKey={(option) => `${option.firstName} ${option.lastName}`} ``` -------------------------------- ### useAsync & withAsync HOC Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md Higher-Order Component used in `AsyncTypeahead`. ```APIDOC ## useAsync & withAsync ### Description The HOC used in [`AsyncTypeahead`](#asynctypeahead). ### Method HOC ``` -------------------------------- ### Basic Typeahead Children Rendering Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md Shows the basic usage of providing children directly to the Typeahead component for rendering. This is a simple way to include static content within the typeahead's structure. ```jsx
Render me!
``` -------------------------------- ### TypeaheadInputSingle & TypeaheadInputMulti Components Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md Input components that handle single and multi-selections, respectively. In the multi-select component, selections are rendered as children. ```APIDOC ## TypeaheadInputSingle & TypeaheadInputMulti Components ### Description Input components that handles single- and multi-selections, respectively. In the multi-select component, selections are rendered as children. ### Props #### `disabled` - **Type**: `boolean` - **Default**: `false` - **Description**: Whether or not the input component is disabled. ``` -------------------------------- ### TypeaheadMenu Component Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md The `` component provides a structured menu for typeahead options. ```APIDOC ## ### Description Component providing a structured menu for typeahead options. ### Method N/A (Component) ### Endpoint N/A (Component) ### Parameters #### Props (Specific props for `` would be listed here, but are not detailed in the provided text.) ### Request Example N/A (Component) ### Response N/A (Component) ``` -------------------------------- ### Token Component Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md Individual token component, used for customizing `Token` contents within `renderToken`. ```APIDOC ## Token Component ### Description Individual token component, most commonly for use within `renderToken` to customize the `Token` contents. ### Props #### `option` - **Type**: `Object | string` - **Required**: Yes - **Description**: The data item to be displayed. #### `disabled` - **Type**: `boolean` - **Default**: `false` - **Description**: Whether the token is in a disabled state. If `true` it will not be interactive or removeable. #### `href` - **Type**: `string` - **Description**: If provided, the token will be rendered with an `` tag and `href` attribute. #### `readOnly` - **Type**: `boolean` - **Default**: `false` - **Description**: Whether the token is in a read-only state. If `true` it will not be removeable, but it will be interactive if provided an `href`. #### `tabIndex` - **Type**: `number` - **Default**: `0` - **Description**: Allows the tabindex to be set if something other than the default is desired. ``` -------------------------------- ### Allow New Option Callback Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md Defines a callback function to determine if a user-defined option should be included in the results list. The callback receives the current results and props, returning a boolean to indicate inclusion. This is useful for validating or conditionally adding new entries. ```javascript allowNew={(results, props) => { // Custom logic to decide if a new entry should be allowed return true; }} ``` -------------------------------- ### Basic Typeahead with String Array in React Source: https://context7.com/ericgio/react-bootstrap-typeahead/llms.txt Demonstrates a basic single-selection typeahead component using a simple array of strings as its data source. It requires the Typeahead component and its CSS, and utilizes React's useState hook to manage the selected option. ```jsx import { Typeahead } from 'react-bootstrap-typeahead'; import 'react-bootstrap-typeahead/css/Typeahead.css'; function BasicExample() { const [selected, setSelected] = useState([]); const options = ['JavaScript', 'Python', 'Java', 'C++', 'Ruby', 'Go', 'Rust']; return ( ); } ``` -------------------------------- ### Import Typeahead component in React Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/README.md Demonstrates how to import the Typeahead component into your React project using ES2015 modules or CommonJS syntax. This allows you to use the component in your JSX. ```jsx import { Typeahead } from 'react-bootstrap-typeahead'; // ES2015 ``` ```javascript var Typeahead = require('react-bootstrap-typeahead').Typeahead; // CommonJS ``` -------------------------------- ### Token Component Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md The `` component is used to display selected items in a multi-select typeahead. ```APIDOC ## ### Description Component used to display selected items in a multi-select typeahead. ### Method N/A (Component) ### Endpoint N/A (Component) ### Parameters #### Props (Specific props for `` would be listed here, but are not detailed in the provided text.) ### Request Example N/A (Component) ### Response N/A (Component) ``` -------------------------------- ### Input Event Handlers (onBlur, onFocus, onKeyDown) Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md Standard input event handlers that are called when the typeahead input field receives blur, focus, or keydown events. These allow for custom logic to be executed on these user interactions. ```javascript onBlur={(event) => { console.log('Input blurred'); }} onFocus={(event) => { console.log('Input focused'); }} onKeyDown={(event) => { console.log('Key pressed:', event.key); }} ``` -------------------------------- ### Controlled vs Uncontrolled Component Usage Source: https://context7.com/ericgio/react-bootstrap-typeahead/llms.txt Illustrates the difference between controlled and uncontrolled components using the Typeahead. The controlled version is recommended for better state management. Requires React and react-bootstrap-typeahead. ```jsx import { Typeahead } from 'react-bootstrap-typeahead'; // Controlled Component (Recommended) function ControlledExample() { const [selected, setSelected] = useState([]); const options = ['Option 1', 'Option 2', 'Option 3']; const handleChange = (selectedOptions) => { console.log('Selection changed:', selectedOptions); setSelected(selectedOptions); // Can perform additional logic here if (selectedOptions.length > 0) { // Do something with the selection } }; return ( ); } // Uncontrolled Component function UncontrolledExample() { const options = ['Option 1', 'Option 2', 'Option 3']; const defaultSelected = ['Option 1']; const handleChange = (selectedOptions) => { console.log('Selection changed:', selectedOptions); // State is managed internally by the component }; return ( ); } ``` -------------------------------- ### Include Typeahead CSS module Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/README.md Shows how to import the necessary CSS for the react-bootstrap-typeahead component as a module within your JavaScript files. This ensures proper styling for the typeahead elements. ```javascript import 'react-bootstrap-typeahead/css/Typeahead.css'; ``` -------------------------------- ### Typeahead Children as Render Function Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md Demonstrates using a render function as a child of the Typeahead component. This allows the component to pass down its internal state to the child, enabling dynamic rendering based on the typeahead's current status, such as loading or search prompts. ```jsx {(state) => (
Render me!
)}
``` -------------------------------- ### React: Allowing New Entries with Typeahead Source: https://context7.com/ericgio/react-bootstrap-typeahead/llms.txt Shows how to enable users to add new options to the typeahead component, including conditional logic for validation before allowing a new entry. This is useful for dynamic tag creation or custom data input. ```jsx import { Typeahead } from 'react-bootstrap-typeahead'; import { useState } from 'react'; function AllowNewExample() { const [selected, setSelected] = useState([]); const [tags, setTags] = useState(['JavaScript', 'Python', 'Java', 'React', 'Node.js']); const handleChange = (selectedOptions) => { setSelected(selectedOptions); // Add new custom tags to the options list selectedOptions.forEach((option) => { if (option.customOption && !tags.includes(option.label)) { setTags([...tags, option.label]); } }); }; return ( ); } // Conditional allowNew with validation function ConditionalAllowNewExample() { const [selected, setSelected] = useState([]); const emails = ['john@example.com', 'jane@example.com', 'bob@example.com']; const validateEmail = (email) => { return /^[^s@]+@[^s@]+\.[^s@]+$/.test(email); }; const shouldAllowNew = (results, props) => { return validateEmail(props.text.trim()); }; return ( ); } ``` -------------------------------- ### AsyncTypeahead for Remote Data Fetching in React Source: https://context7.com/ericgio/react-bootstrap-typeahead/llms.txt Features the `AsyncTypeahead` component for fetching data asynchronously from a remote API. It includes loading state management, debouncing via `minLength`, and custom rendering for menu items using the `renderMenuItemChildren` prop. ```jsx import { AsyncTypeahead } from 'react-bootstrap-typeahead'; import 'react-bootstrap-typeahead/css/Typeahead.css'; function AsyncExample() { const [isLoading, setIsLoading] = useState(false); const [options, setOptions] = useState([]); const [selected, setSelected] = useState([]); const handleSearch = async (query) => { setIsLoading(true); try { const response = await fetch( `https://api.github.com/search/users?q=${query}` ); const data = await response.json(); setOptions(data.items); } catch (error) { console.error('Error fetching users:', error); setOptions([]); } finally { setIsLoading(false); } }; return ( (
{option.login} {option.login}
)} /> ); } ``` -------------------------------- ### Include Bootstrap 5 CSS for Typeahead Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/README.md Instructions for including the specific CSS file (`Typeahead.bs5.css`) required for compatibility with Bootstrap 5. This should be used alongside the base CSS file for Bootstrap 5 projects. ```html ``` -------------------------------- ### onPaginate Event Handler Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md Triggered when the pagination menu item is clicked, allowing users to display additional results. The handler receives the event object and the count of currently shown results. ```javascript onPaginate={(event, shownResults) => { console.log('Pagination clicked, showing:', shownResults); }} ``` -------------------------------- ### Custom Input with Hint Component Source: https://context7.com/ericgio/react-bootstrap-typeahead/llms.txt Shows how to customize the input element of the Typeahead using the `renderInput` prop, allowing for custom styling and integration with other components like Bootstrap's FloatingLabel. Requires React, react-bootstrap, and react-bootstrap-typeahead. ```jsx import { Typeahead, Hint } from 'react-bootstrap-typeahead'; import { Form } from 'react-bootstrap'; function CustomInputExample() { const [selected, setSelected] = useState([]); const options = ['JavaScript', 'Java', 'Python', 'Ruby', 'Go', 'Rust']; return ( ( { inputRef(node); referenceElementRef(node); }} type="text" /> )} /> ); } ``` -------------------------------- ### React: Text Highlighting with Highlighter Component in Typeahead Source: https://context7.com/ericgio/react-bootstrap-typeahead/llms.txt Demonstrates using the Highlighter component within react-bootstrap-typeahead to visually emphasize matching text in dropdown menu items. This improves user experience by making search results more prominent. ```jsx import { Typeahead, Highlighter } from 'react-bootstrap-typeahead'; import { useState } from 'react'; function HighlighterExample() { const [selected, setSelected] = useState([]); const countries = [ { id: 1, name: 'United States', code: 'US', capital: 'Washington' }, { id: 2, name: 'United Kingdom', code: 'UK', capital: 'London' }, { id: 3, name: 'Canada', code: 'CA', capital: 'Ottawa' }, { id: 4, name: 'Australia', code: 'AU', capital: 'Canberra' } ]; return ( (
{option.name}
{option.capital} {' - '} {option.code}
)} /> ); } ``` -------------------------------- ### Filtering Configuration (filterBy) Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md Specifies how the typeahead filters options. It can accept an array of strings to filter by specific keys or a custom function for complex filtering logic. Refer to the Filtering section for detailed usage. ```javascript filterBy={['name', 'email']} // Or with a custom function: filterBy={(option, text) => { return option.name.includes(text) || option.email.includes(text); }} ``` -------------------------------- ### Include Typeahead CSS via HTML link Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/README.md Provides an alternative method for including the react-bootstrap-typeahead CSS by linking to the stylesheet directly in your HTML file. This is useful for projects not using module bundlers. ```html ``` -------------------------------- ### onChange Event Handler Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/API.md A function that is invoked whenever the set of selected items changes. It always receives an array of selected items, regardless of whether multi-selection is enabled. This is crucial for managing the state of selected options. ```javascript onChange={(selected) => { console.log('Selected:', selected); }} ``` -------------------------------- ### Accessing and Using Typeahead Public Methods with Refs (React JSX) Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/Methods.md This snippet demonstrates how to use React's createRef to access the public methods of the Typeahead component. It shows how to attach a ref to the Typeahead instance and then call methods like clear() via the ref's current property. This allows for programmatic control over the component's state and behavior. ```jsx const ref = React.createRef(); <> ``` -------------------------------- ### Basic Typeahead Usage in React JSX Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/Usage.md Demonstrates the fundamental usage of the Typeahead component, requiring an array of data options for filtering and display. The `onChange` prop handles user selections. ```jsx { // Handle selections... }} options={[ /* Array of objects or strings */ ]} /> ``` -------------------------------- ### Public Methods Source: https://github.com/ericgio/react-bootstrap-typeahead/blob/main/docs/Methods.md Access and utilize the component's public methods by passing a ref to the Typeahead component. ```APIDOC ## Public Methods To access the component's public methods, pass a ref to your typeahead then access the ref in your code: ```jsx const ref = React.createRef(); <> ``` ### Methods - **blur()** - Description: Blurs the input. - **clear()** - Description: Resets the typeahead component. Clears both text and selection(s). - **focus()** - Description: Focuses the input. - **getInput()** - Description: Provides access to the component's input node. - **hideMenu()** - Description: Hides the menu. - **toggleMenu()** - Description: Shows the menu if it is currently hidden; hides the menu if it is currently shown. ```