API Reference

October 1, 2024 ยท View on GitHub

The components and higher-order components (HOCs) described below are publicly exposed in the top-level module. Other components should be considered private and subject to change without notice.

Components

Higher-Order Components & Hooks

Components

<Typeahead>

The primary component provided by the module.

Props

NameTypeDefaultDescription
align'justify' | 'left' | 'right''justify'Specify menu alignment. The default value is justify, which makes the menu as wide as the input and truncates long values. Specifying left or right will align the menu to that side and the width will be determined by the length of menu item values.
allowNewboolean | functionfalseSpecifies whether or not arbitrary, user-defined options may be added to the result set. New entries will be included when the trimmed input is truthy and there is no exact match in the result set.

If a function is specified, allows for a callback to decide whether the new entry menu item should be included in the results list. The callback should return a boolean value:

(results: Array<Object|string>, props: Object) => boolean
autoFocusbooleanfalseAutofocus the input when the component initially mounts.
caseSensitivebooleanfalseWhether or not filtering should be case-sensitive.
clearButtonbooleanfalseDisplays a button to clear the input when there are selections.
defaultInputValuestring''The initial value displayed in the text input.
defaultOpenbooleanfalseWhether or not the menu is displayed upon initial render.
defaultSelectedArray<Object|string>[]Specify any pre-selected options. Use only if you want the component to be uncontrolled.
disabledbooleanWhether to disable the input. Will also disable selections when multiple={true}.
dropupbooleanfalseSpecify whether the menu should appear above the input.
emptyLabelnode'No matches found.'Message displayed in the menu when there are no valid results.
filterByArray<string> | functionSee full documentation in the Filtering section.
flipbooleanfalseWhether or not to automatically adjust the position of the menu when it reaches the viewport boundaries.
highlightOnlyResultbooleanfalseHighlights the menu item if there is only one result and allows selecting that item by hitting enter. Does not work with allowNew.
id requiredstring or numberAn html id attribute, required for assistive technologies such as screen readers.
ignoreDiacriticsbooleantrueWhether the filter should ignore accents and other diacritical marks.
inputPropsobject{}Props to be applied directly to the input. onBlur, onChange, onFocus, and onKeyDown are ignored.
isInvalidbooleanfalseAdds the is-invalid classname to the form-control. Only affects Bootstrap 4 and above.
isLoadingbooleanfalseIndicate whether an asynchronous data fetch is happening.
isValidbooleanfalseAdds the is-valid classname to the form-control. Only affects Bootstrap 4 and above.
labelKeystring | function'label'See full documentation in the Rendering section.
minLengthnumber0Minimum user input before displaying results.
onChangefunctionInvoked when the set of selections changes (ie: an item is added or removed). For consistency, selected is always an array of selections, even if multi-selection is not enabled.

(selected: Array<Object|string>) => void
onInputChangefunctionInvoked when the input value changes. Receives the string value of the input (text), as well as the original event.

(text: string, event: Event) => void
onBlur, onFocus, onKeyDownfunctionAs with a normal text input, these are called when the typeahead input has blur, focus, or keydown events.

(event: Event) => void
onMenuTogglefunctionInvoked when menu visibility changes.

(isOpen: boolean) => void
onPaginatefunctionInvoked when the pagination menu item is clicked. Receives an event as the first argument and the number of shown results as the second.

(event: Event, shownResults: number) => void
openbooleanWhether or not the menu should be displayed. undefined allows the component to control visibility, while true and false show and hide the menu, respectively.
options requiredArray<Object|string>Full set of options, including any pre-selected options.
paginatebooleantrueGive user the ability to display additional results if the number of results exceeds maxResults.
paginationTextstring'Display additional results...'Prompt displayed when large data sets are paginated.
placeholderstringPlaceholder text for the input.
positionFixedbooleanfalseWhether to use fixed positioning for the menu, which is useful when rendering inside a container with overflow: hidden;. Uses absolute positioning by default.
renderInputfunctionCallback for custom input rendering. See full documentation in the Rendering section.
renderMenufunctionCallback for custom menu rendering. See full documentation in the Rendering section.
renderMenuItemChildrenfunctionCallback for customized rendering of menu item contents. See full documentation in the Rendering section.
renderTokenfunctionCallback for custom token rendering. See full documentation in the Rendering section.
selectedArray<Object|string>[]The selected option(s) displayed in the input. Use this prop if you want to control the component via its parent.
selectHintfunctionCallback function that determines whether the hint should be selected.

(shouldSelectHint: boolean, KeyboardEvent<HTMLInputElement>) => boolean
size'lg' | 'sm'Specify the size of the input.

Children

In addition to the props listed above, Typeahead also accepts either children or a child render function.

<Typeahead ... >
  <div>Render me!</div>
</Typeahead>

The render function receives partial internal state from the component:

<Typeahead ... >
  {(state) => (
    <div>Render me!</div>
  )}
</Typeahead>

This may be useful for things like customizing the loading indicator or clear button, or including an announcer for accessibility purposes.

<AsyncTypeahead>

An enhanced version of the normal Typeahead component for use when performing asynchronous searches. Provides debouncing of user input, optional query caching, and search prompt, empty results, and pending request behaviors.

<AsyncTypeahead
  isLoading={this.state.isLoading}
  labelKey={option => `${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}
/>

Note that this component is the same as:

import { Typeahead, withAsync } from 'react-bootstrap-typeahead';

const AsyncTypeahead = withAsync(Typeahead);

Props

NameTypeDefaultDescription
delaynumber200Delay, in milliseconds, before performing search.
isLoading requiredbooleanWhether or not an asynchronous request is in progress.
onSearch requiredfunctionCallback to perform when the search is executed, where query is the input string.

(query: string) => void
optionsArray<Object|string>[]Options to be passed to the typeahead. Will typically be the query results, but can also be initial default options.
promptTextnode'Type to search...'Message displayed in the menu when there is no user input.
searchTextnode'Searching...'Message to display in the menu while the request is pending.
useCachebooltrueWhether or not the component should cache query results.

<Highlighter>

Component for highlighting substring matches in the menu items.

<Typeahead
  ...
  renderMenuItemChildren={(option, props, idx) => (
    <Highlighter search={props.text}>
      {option[props.labelKey]}
    </Highlighter>
  )}
/>

Props

NameTypeDefaultDescription
children (required)stringHighlighter expects a string as the only child.
highlightClassNamestring'rbt-highlight-text'Classname applied to the highlighted text.
search (required)stringThe substring to look for. This value should correspond to the input text of the typeahead and can be obtained via the onInputChange prop or from the text property of props being passed down via renderMenu or renderMenuItemChildren.

<Hint>

The Hint component can be used to wrap custom inputs.

<Typeahead
  ...
  renderInput={({ inputRef, referenceElementRef, ...inputProps }) => (
    <Hint>
      <FloatingLabel controlId="name" label="Name">
        <Form.Control
          {...inputProps}
          ref={(node) => {
            inputRef(node);
            referenceElementRef(node);
          }}
          type="text"
        />
      </FloatingLabel>
    </Hint>
  )}
/>

Props

NameTypeDefaultDescription
children (required)node

<Input>

Abstract <input> component that handles an inputRef prop and is used as the basis for both single- and multi-select input components.

Provides the markup for a Bootstrap menu, along with some extra functionality for specifying a label when there are no results.

NameTypeDefaultDescription
emptyLabelnode'No matches found.'Message to display in the menu if there are no valid results.
id requiredstring | numberId value required for accessibility.
maxHeightstring'300px'Maximum height of the dropdown menu.

Provides the markup for a Bootstrap menu item, but is wrapped by the withItem HOC to ensure proper behavior within the typeahead context. Provided for use if a more customized Menu is desired.

Props

NameTypeDefaultDescription
option (required)Object | stringThe data item to be displayed.
positionnumberThe 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.

<TypeaheadInputSingle> & <TypeaheadInputMulti>

Input components that handles single- and multi-selections, respectively. In the multi-select component, selections are rendered as children.

Props

NameTypeDefaultDescription
disabledbooleanfalseWhether or not the input component is disabled.

<TypeaheadMenu>

The default menu which is rendered by the Typeahead component. Can be used in a custom renderMenu function for wrapping or modifying the props passed to it without having to re-implement the default functionality.

Props

NameTypeDefaultDescription
labelKey requiredstring | functionSee full documentation in the Rendering section.
newSelectionPrefixstring'New selection: 'Provides the ability to specify a prefix before the user-entered text to indicate that the selection will be new. No-op unless allowNew={true}.
paginationTextstring'Display additional results...'Prompt displayed when large data sets are paginated.
renderMenuItemChildrenfunctionProvides a hook for customized rendering of menu item contents.
text requiredstringThe current value of the typeahead's input.

<Token>

Individual token component, most commonly for use within renderToken to customize the Token contents.

Props

NameTypeDefaultDescription
option (required)Object | stringThe data item to be displayed.
disabledbooleanfalseWhether the token is in a disabled state. If true it will not be interactive or removeable.
hrefstringIf provided, the token will be rendered with an <a> tag and href attribute.
readOnlybooleanfalseWhether the token is in a read-only state. If true it will not be removeable, but it will be interactive if provided an href.
tabIndexnumber0Allows the tabindex to be set if something other than the default is desired.

Higher-Order Components & Hooks

useAsync & withAsync

The HOC used in AsyncTypeahead.

useItem & withItem

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:

import { MenuItem } from 'react-bootstrap';
import { Menu, Typeahead, useItem, withItem } from 'react-bootstrap-typeahead';

const Item = withItem(MenuItem);

// OR

const Item = (props) => <MenuItem {...useItem(props)} />;

<Typeahead
  renderMenu={(results, menuProps) => (
    <Menu {...menuProps}>
      {results.map((option, position) => (
        <Item option={option} position={position}>
          {option.label}
        </Item>
      ))}
    </Menu>
  )}
/>

useToken & withToken

Encapsulates keystroke and outside click behaviors used in Token. Useful if you want completely custom markup for the token. The hook and the HOC provide the following props to be consumed by the token component:

NameTypeDescription
activebooleanWhether the token is active or not. Useful for adding an "active" classname to the component for styling.
onBlurfunctionCallback invoked when the token loses focus. Should be applied to the top-level element.
onClickfunctionCallback invoked when the token is clicked. Should be applied to the top-level element.
onFocusfunctionCallback invoked when the token is focused. Should be applied to the top-level element.
onKeyDownfunctionCallback invoked when the token is focused and a key is pressed. Should be applied to the top-level element.
onRemovefunctionCallback used to handle token removal. This typically would be applied to the onClick handler of a "remove" or "x" button in the token.
refUsed for detecting clicks outside the token and updating internal state accordingly. Should be applied to the top-level DOM node.
// Important: use `forwardRef` to pass the ref on to the underlying DOM nodes.
const MyToken = forwardRef(({ active, onRemove, ...props }, ref) => (
  <div
    {...props}
    className={active ? 'active' : ''}
    ref={ref}>
    <button onClick={onRemove}>
      x
    </button>
  </div>
));

// HOC
const CustomToken = withToken(MyToken);

// Hook
const CustomToken = (props) => <MyToken {...useToken(props)} />;

If using the hook, you can also apply it directly within your token component:

const MyToken = (props) => {
  const { active, onRemove, ref, ...otherProps } = useToken(props);

  return (
    <div
      {...otherProps}
      className={active ? 'active' : ''}
      ref={ref}>
      <button onClick={onRemove}>
        x
      </button>
    </div>
  );
};

useHint

Hook for adding a hint to a custom input. Mainly useful if you'd like to customize the hint's markup.

const CustomHint = (props) => {
  const { hintRef, hintText } = useHint(props);

  return (
    <div ... >
      {props.children}
      <input
        ...
        ref={hintRef}
        value={hintText}
      />
    </div>
  );
};

See the Hint component for an example of how to apply useHint.