UNPKG

17.4 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.
67selectHint | function | | Callback function that determines whether the hint should be selected.<br><br><pre>`(shouldSelectHint: boolean, KeyboardEvent<HTMLInputElement>) => boolean`</pre>
68size | `'lg'` \| `'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.
149
150```jsx
151<Typeahead
152 ...
153 renderInput={({ inputRef, referenceElementRef ...inputProps }) => (
154 <Hint>
155 <FloatingLabel controlId="name" label="Name">
156 <Form.Control
157 {...inputProps}
158 ref={(node) => {
159 inputRef(node);
160 referenceElementRef(node);
161 }}
162 type="text"
163 />
164 </FloatingLabel>
165 </Hint>
166 )}
167/>
168```
169
170#### Props
171Name | Type | Default | Description
172-----|------|---------|------------
173children `(required)` | node | |
174
175### `<Input>`
176Abstract `<input>` component that handles an `inputRef` prop and is used as the basis for both single- and multi-select input components.
177
178### `<Menu>`
179Provides the markup for a Bootstrap menu, along with some extra functionality for specifying a label when there are no results.
180
181Name | Type | Default | Description
182-----|------|---------|------------
183emptyLabel | node | `'No matches found.'` | Message to display in the menu if there are no valid results.
184id `required` | string \| number | | Id value required for accessibility.
185maxHeight | string | `'300px'` | Maximum height of the dropdown menu.
186
187### `<MenuItem>`
188Provides 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.
189
190#### Props
191Name | Type | Default | Description
192-----|------|---------|------------
193option `(required)` | Object \| string | | The data item to be displayed.
194position | 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.
195
196### `<TypeaheadInputSingle>` & `<TypeaheadInputMulti>`
197Input components that handles single- and multi-selections, respectively. In the multi-select component, selections are rendered as children.
198
199#### Props
200Name | Type | Default | Description
201-----|------|---------|------------
202disabled | boolean | `false` | Whether or not the input component is disabled.
203
204### `<TypeaheadMenu>`
205The 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.
206
207#### Props
208Name | Type | Default | Description
209-----|------|---------|------------
210labelKey `required` | string \| function | | See full documentation in the [Rendering section](Rendering.md#labelkey-string--function).
211newSelectionPrefix | 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}`.
212paginationText | string | `'Display additional results...'` | Prompt displayed when large data sets are paginated.
213renderMenuItemChildren | function | | Provides a hook for customized rendering of menu item contents.
214text `required` | string | | The current value of the typeahead's input.
215
216### `<Token>`
217Individual token component, most commonly for use within `renderToken` to customize the `Token` contents.
218
219#### Props
220Name | Type | Default | Description
221-----|------|---------|------------
222option `(required)` | Object \| string | | The data item to be displayed.
223disabled | boolean | `false` | Whether the token is in a disabled state. If `true` it will not be interactive or removeable.
224href | string | | If provided, the token will be rendered with an `<a>` tag and `href` attribute.
225readOnly | 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`.
226tabIndex | number | `0` | Allows the tabindex to be set if something other than the default is desired.
227
228## Higher-Order Components & Hooks
229
230### `useAsync` & `withAsync`
231The HOC used in [`AsyncTypeahead`](#asynctypeahead).
232
233### `useItem` & `withItem`
234Connects 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.
235
236If you use your own menu item components (in `renderMenu` for example), you are strongly advised to use either the hook or the HOC:
237
238```jsx
239import { MenuItem } from 'react-bootstrap';
240import { Menu, Typeahead, useItem, withItem } from 'react-bootstrap-typeahead';
241
242const Item = withItem(MenuItem);
243
244// OR
245
246const Item = (props) => <MenuItem {...useItem(props)} />;
247
248<Typeahead
249 renderMenu={(results, menuProps) => (
250 <Menu {...menuProps}>
251 {results.map((option, position) => (
252 <Item option={option} position={position}>
253 {option.label}
254 </Item>
255 ))}
256 </Menu>
257 )}
258/>
259```
260
261### `useToken` & `withToken`
262Encapsulates 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:
263
264Name | Type | Description
265-----|------|------------
266active | boolean | Whether the token is active or not. Useful for adding an "active" classname to the component for styling.
267onBlur | function | Callback invoked when the token loses focus. Should be applied to the top-level element.
268onClick | function | Callback invoked when the token is clicked. Should be applied to the top-level element.
269onFocus | function | Callback invoked when the token is focused. Should be applied to the top-level element.
270onKeyDown | function | Callback invoked when the token is focused and a key is pressed. Should be applied to the top-level element.
271onRemove | 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.
272ref | Used for detecting clicks outside the token and updating internal state accordingly. Should be applied to the top-level DOM node.
273
274```jsx
275// Important: use `forwardRef` to pass the ref on to the underlying DOM nodes.
276const MyToken = forwardRef(({ active, onRemove, ...props }, ref) => (
277 <div
278 {...props}
279 className={active ? 'active' : ''}
280 ref={ref}>
281 <button onClick={onRemove}>
282 x
283 </button>
284 </div>
285));
286
287// HOC
288const CustomToken = withToken(MyToken);
289
290// Hook
291const CustomToken = (props) => <MyToken {...useToken(props)} />;
292```
293If using the hook, you can also apply it directly within your token component:
294```jsx
295const MyToken = (props) => {
296 const { active, onRemove, ref, ...otherProps } = useToken(props);
297
298 return (
299 <div
300 {...otherProps}
301 className={active ? 'active' : ''}
302 ref={ref}>
303 <button onClick={onRemove}>
304 x
305 </button>
306 </div>
307 );
308};
309```
310
311### `useHint`
312Hook for adding a hint to a custom input. Mainly useful if you'd like to customize the hint's markup.
313
314```jsx
315const CustomHint = (props) => {
316 const { hintRef, hintText } = useHint(props);
317
318 return (
319 <div ... >
320 {props.children}
321 <input
322 ...
323 ref={hintRef}
324 value={hintText}
325 />
326 </div>
327 );
328};
329```
330See 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`.