UNPKG

18 kBMarkdownView Raw
1# API Reference
2The 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.
3
4#### [Components](#components-1)
5- [`<Typeahead>`](#typeahead)
6- [`<AsyncTypeahead>`](#asynctypeahead)
7- [`<Highlighter>`](#highlighter)
8- [`<Hint>`](#hint)
9- [`<Input>`](#input)
10- [`<Menu>`](#menu)
11- [`<MenuItem>`](#menuitem)
12- [`<TypeaheadInputSingle>` & `<TypeaheadInputMulti>`](#typeaheadinputsingle--typeaheadinputmulti)
13- [`<TypeaheadMenu>`](#typeaheadmenu)
14- [`<Token>`](#token)
15
16#### [Higher-Order Components & Hooks](#higher-order-components--hooks-1)
17- [`useAsync` & `withAsync`](#useasync--withasync)
18- [`useItem` & `withItem`](#useitem--withitem)
19- [`useToken` & `withToken`](#usetoken--withtoken)
20- [`useHint`](#useHint)
21
22## Components
23
24### `<Typeahead>`
25The primary component provided by the module.
26
27#### Props
28Name | Type | Default | Description
29-----|------|---------|------------
30align | `'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.
31allowNew | boolean \| function | `false` | Specifies 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.<br><br>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:<br><br><pre>`(results: Array<Object\|string>, props: Object) => boolean`</pre>
32autoFocus | boolean | `false` | Autofocus the input when the component initially mounts.
33caseSensitive | boolean | `false` | Whether or not filtering should be case-sensitive.
34clearButton | boolean | `false` | Displays a button to clear the input when there are selections.
35defaultInputValue | string | `''` | The initial value displayed in the text input.
36defaultOpen | boolean | `false` | Whether or not the menu is displayed upon initial render.
37defaultSelected | Array\<Object\|string\> | `[]` | Specify any pre-selected options. Use only if you want the component to be uncontrolled.
38disabled | boolean | | Whether to disable the input. Will also disable selections when `multiple={true}`.
39dropup | boolean | `false` | Specify whether the menu should appear above the input.
40emptyLabel | node | `'No matches found.'` | Message displayed in the menu when there are no valid results.
41filterBy | Array\<string\> \| function | | See full documentation in the [Filtering section](Filtering.md#filterby-arraystring--function).
42flip | boolean | false | Whether or not to automatically adjust the position of the menu when it reaches the viewport boundaries.
43highlightOnlyResult | boolean | false | Highlights the menu item if there is only one result and allows selecting that item by hitting enter. Does not work with `allowNew`.
44id `required` | string or number | | An html id attribute, required for assistive technologies such as screen readers.
45ignoreDiacritics | boolean | true | Whether the filter should ignore accents and other diacritical marks.
46inputProps | object | {} | Props to be applied directly to the input. `onBlur`, `onChange`, `onFocus`, and `onKeyDown` are ignored.
47isInvalid | boolean | false | Adds the `is-invalid` classname to the `form-control`. Only affects Bootstrap 4.
48isLoading | boolean | false | Indicate whether an asynchronous data fetch is happening.
49isValid | boolean | false | Adds the `is-valid` classname to the `form-control`. Only affects Bootstrap 4.
50labelKey | string \| function | `'label'` | See full documentation in the [Rendering section](Rendering.md#labelkey-string--function).
51onChange | function | | Invoked 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. <br><br><pre>`(selected: Array<Object\|string>) => void`</pre>
52onInputChange | function | | Invoked when the input value changes. Receives the string value of the input (`text`), as well as the original event. <br><br><pre>`(text: string, event: Event) => void`</pre>
53onBlur, onFocus, onKeyDown | function | | As with a normal text input, these are called when the typeahead input has blur, focus, or keydown events. <br><br><pre>`(event: Event) => void`</pre>
54onMenuToggle | function | | Invoked when menu visibility changes. <br><br><pre>`(isOpen: boolean) => void`</pre>
55onPaginate | `function` | | Invoked when the pagination menu item is clicked. Receives an event as the first argument and the number of shown results as the second. <br><br><pre>`(event: Event, shownResults: number) => void`</pre>
56open | boolean | | Whether or not the menu should be displayed. `undefined` allows the component to control visibility, while `true` and `false` show and hide the menu, respectively.
57options `required` | Array\<Object\|string\> | | Full set of options, including any pre-selected options.
58paginate | boolean | `true` | Give user the ability to display additional results if the number of results exceeds `maxResults`.
59paginationText | string | `'Display additional results...'` | Prompt displayed when large data sets are paginated.
60placeholder | string | | Placeholder text for the input.
61positionFixed | boolean | `false` | Whether to use fixed positioning for the menu, which is useful when rendering inside a container with `overflow: hidden;`. Uses absolute positioning by default.
62renderInput | function | | Callback for custom input rendering. See full documentation in the [Rendering section](Rendering.md#renderinputinputprops-object-state-object).
63renderMenu | function | | Callback for custom menu rendering. See full documentation in the [Rendering section](Rendering.md#rendermenuresults-arrayobjectstring-menuprops-object-state-object).
64renderMenuItemChildren | function | | Callback for customized rendering of menu item contents. See full documentation in the [Rendering section](Rendering.md#rendermenuitemchildrenoption-objectstring-props-object-index-number).
65renderToken | function | | Callback for custom token rendering. See full documentation in the [Rendering section](Rendering.md#rendertokenoption-objectstring-props-object-index-number).
66selected | Array\<Object\|string\> | `[]` | The selected option(s) displayed in the input. Use this prop if you want to control the component via its parent.
67selectHintOnEnter | boolean | `false` | `DEPRECATED`: Use `shouldSelect` prop on `Hint` component or `shouldSelectHint` prop on `TypeaheadInputSingle` & `TypeaheadInputMulti`. Allows selecting the hinted result by pressing enter.
68size | `'large'` \| `'lg'` \| `'small'` \| `'sm'` | | Specify the size of the input.
69
70#### Children
71In addition to the props listed above, `Typeahead` also accepts either children or a child render function.
72
73```jsx
74<Typeahead ... >
75 <div>Render me!</div>
76</Typeahead>
77```
78The render function receives partial internal state from the component:
79```jsx
80<Typeahead ... >
81 {(state) => (
82 <div>Render me!</div>
83 )}
84</Typeahead>
85```
86This may be useful for things like customizing the loading indicator or clear button, or including an announcer for accessibility purposes.
87
88### `<AsyncTypeahead>`
89An 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.
90
91```jsx
92<AsyncTypeahead
93 isLoading={this.state.isLoading}
94 labelKey={option => `${option.login}`}
95 onSearch={(query) => {
96 this.setState({isLoading: true});
97 fetch(`https://api.github.com/search/users?q=${query}`)
98 .then(resp => resp.json())
99 .then(json => this.setState({
100 isLoading: false,
101 options: json.items,
102 }));
103 }}
104 options={this.state.options}
105/>
106```
107
108Note that this component is the same as:
109```jsx
110import { Typeahead, withAsync } from 'react-bootstrap-typeahead';
111
112const AsyncTypeahead = withAsync(Typeahead);
113```
114
115#### Props
116Name | Type | Default | Description
117-----|------|---------|------------
118delay | number | `200` | Delay, in milliseconds, before performing search.
119isLoading `required` | boolean | | Whether or not an asynchronous request is in progress.
120onSearch `required` | function | | Callback to perform when the search is executed, where `query` is the input string.<br><br><pre>`(query: string) => void`</pre>
121options | Array\<Object\|string\> | `[]` | Options to be passed to the typeahead. Will typically be the query results, but can also be initial default options.
122promptText | node | `'Type to search...'` | Message displayed in the menu when there is no user input.
123searchText | node | `'Searching...'` | Message to display in the menu while the request is pending.
124useCache | bool | `true` | Whether or not the component should cache query results.
125
126### `<Highlighter>`
127Component for highlighting substring matches in the menu items.
128
129```jsx
130<Typeahead
131 ...
132 renderMenuItemChildren={(option, props, idx) => (
133 <Highlighter search={props.text}>
134 {option[props.labelKey]}
135 </Highlighter>
136 )}
137/>
138```
139
140#### Props
141Name | Type | Default | Description
142-----|------|---------|------------
143children `(required)` | string | | `Highlighter` expects a string as the only child.
144highlightClassName | string | `'rbt-highlight-text'` | Classname applied to the highlighted text.
145search `(required)` | string | | The 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`.
146
147### `<Hint>`
148The `Hint` component can be used to wrap custom inputs. The `shouldSelect` prop allows you to define the conditions under which the hint should be selected.
149
150```jsx
151<Typeahead
152 ...
153 renderInput={({ inputRef, ...inputProps }) => (
154 <Hint
155 shouldSelect={(shouldSelect, e) => {
156 // Selects the hint when the user hits the 'enter' key.
157 return e.keyCode === 13 || shouldSelect;
158 }}>
159 <MyInput {...inputProps} ref={inputRef} />
160 </Hint>
161 )}
162/>
163```
164
165#### Props
166Name | Type | Default | Description
167-----|------|---------|------------
168children `(required)` | node | | `Hint` expects a single child: your input component.
169shouldSelect | function | | Callback function that determines whether the hint should be selected.<br><br><pre>`(shouldSelect: boolean, SyntheticKeyboardEvent<HTMLInputElement>) => boolean`</pre>
170
171### `<Input>`
172Abstract `<input>` component that handles an `inputRef` prop and is used as the basis for both single- and multi-select input components.
173
174### `<Menu>`
175Provides the markup for a Bootstrap menu, along with some extra functionality for specifying a label when there are no results.
176
177Name | Type | Default | Description
178-----|------|---------|------------
179emptyLabel | node | `'No matches found.'` | Message to display in the menu if there are no valid results.
180id `required` | string \| number | | Id value required for accessibility.
181maxHeight | string | `'300px'` | Maximum height of the dropdown menu.
182
183### `<MenuItem>`
184Provides 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.
185
186#### Props
187Name | Type | Default | Description
188-----|------|---------|------------
189option `(required)` | Object \| string | | The data item to be displayed.
190position | number | | 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.
191
192### `<TypeaheadInputSingle>` & `<TypeaheadInputMulti>`
193Input components that handles single- and multi-selections, respectively. In the multi-select component, selections are rendered as children.
194
195#### Props
196Name | Type | Default | Description
197-----|------|---------|------------
198disabled | boolean | `false` | Whether or not the input component is disabled.
199shouldSelectHint | function | | Callback function passed down to `Hint` component to define whether or not the hint should be selected under certain conditions. See the `shouldSelect` prop of `Hint`.
200
201### `<TypeaheadMenu>`
202The 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.
203
204#### Props
205Name | Type | Default | Description
206-----|------|---------|------------
207labelKey `required` | string \| function | | See full documentation in the [Rendering section](Rendering.md#labelkey-string--function).
208newSelectionPrefix | string | `'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}`.
209paginationText | string | `'Display additional results...'` | Prompt displayed when large data sets are paginated.
210renderMenuItemChildren | function | | Provides a hook for customized rendering of menu item contents.
211text `required` | string | | The current value of the typeahead's input.
212
213### `<Token>`
214Individual token component, most commonly for use within `renderToken` to customize the `Token` contents.
215
216#### Props
217Name | Type | Default | Description
218-----|------|---------|------------
219option `(required)` | Object \| string | | The data item to be displayed.
220disabled | boolean | `false` | Whether the token is in a disabled state. If `true` it will not be interactive or removeable.
221href | string | | If provided, the token will be rendered with an `<a>` tag and `href` attribute.
222readOnly | boolean | `false` | 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`.
223tabIndex | number | `0` | Allows the tabindex to be set if something other than the default is desired.
224
225## Higher-Order Components & Hooks
226
227### `useAsync` & `withAsync`
228The HOC used in [`AsyncTypeahead`](#asynctypeahead).
229
230### `useItem` & `withItem`
231Connects 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.
232
233If you use your own menu item components (in `renderMenu` for example), you are strongly advised to use either the hook or the HOC:
234
235```jsx
236import { MenuItem } from 'react-bootstrap';
237import { Menu, Typeahead, useItem, withItem } from 'react-bootstrap-typeahead';
238
239const Item = withItem(MenuItem);
240
241// OR
242
243const Item = (props) => <MenuItem {...useItem(props)} />;
244
245<Typeahead
246 renderMenu={(results, menuProps) => (
247 <Menu {...menuProps}>
248 {results.map((option, position) => (
249 <Item option={option} position={position}>
250 {option.label}
251 </Item>
252 ))}
253 </Menu>
254 )}
255/>
256```
257
258### `useToken` & `withToken`
259Encapsulates 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:
260
261Name | Type | Description
262-----|------|------------
263active | boolean | Whether the token is active or not. Useful for adding an "active" classname to the component for styling.
264onBlur | function | Callback invoked when the token loses focus. Should be applied to the top-level element.
265onClick | function | Callback invoked when the token is clicked. Should be applied to the top-level element.
266onFocus | function | Callback invoked when the token is focused. Should be applied to the top-level element.
267onKeyDown | function | Callback invoked when the token is focused and a key is pressed. Should be applied to the top-level element.
268onRemove | function | Callback used to handle token removal. This typically would be applied to the `onClick` handler of a "remove" or "x" button in the token.
269ref | Used for detecting clicks outside the token and updating internal state accordingly. Should be applied to the top-level DOM node.
270
271```jsx
272// Important: use `forwardRef` to pass the ref on to the underlying DOM nodes.
273const MyToken = forwardRef(({ active, onRemove, ...props }, ref) => (
274 <div
275 {...props}
276 className={active ? 'active' : ''}
277 ref={ref}>
278 <button onClick={onRemove}>
279 x
280 </button>
281 </div>
282));
283
284// HOC
285const CustomToken = withToken(MyToken);
286
287// Hook
288const CustomToken = (props) => <MyToken {...useToken(props)} />;
289```
290If using the hook, you can also apply it directly within your token component:
291```jsx
292const MyToken = (props) => {
293 const { active, onRemove, ref, ...otherProps } = useToken(props);
294
295 return (
296 <div
297 {...otherProps}
298 className={active ? 'active' : ''}
299 ref={ref}>
300 <button onClick={onRemove}>
301 x
302 </button>
303 </div>
304 );
305};
306```
307
308### `useHint`
309Hook for adding a hint to a custom input. Mainly useful if you'd like to customize the hint's markup. Accepts an object with required `children` and an optional `shouldSelect` callback.
310
311```jsx
312const CustomHint = (props) => {
313 const { child, hintRef, hintText } = useHint(props);
314
315 return (
316 <div ... >
317 {child}
318 <input
319 ...
320 ref={hintRef}
321 value={hintText}
322 />
323 </div>
324 );
325};
326```
327See the [`Hint` component](https://github.com/ericgio/react-bootstrap-typeahead/blob/master/src/components/Hint.js#L136) for an example of how to apply `useHint`.