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