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 | 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>
|
52 | 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>
|
53 | 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>
|
54 | onMenuToggle | function | | Invoked when menu visibility changes. <br><br><pre>`(isOpen: boolean) => void`</pre>
|
55 | 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>
|
56 | 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.
|
57 | options `required` | Array\<Object\|string\> | | Full set of options, including any pre-selected options.
|
58 | paginate | boolean | `true` | Give user the ability to display additional results if the number of results exceeds `maxResults`.
|
59 | paginationText | string | `'Display additional results...'` | Prompt displayed when large data sets are paginated.
|
60 | placeholder | string | | Placeholder text for the input.
|
61 | 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.
|
62 | renderInput | function | | Callback for custom input rendering. See full documentation in the [Rendering section](Rendering.md#renderinputinputprops-object-state-object).
|
63 | renderMenu | function | | Callback for custom menu rendering. See full documentation in the [Rendering section](Rendering.md#rendermenuresults-arrayobjectstring-menuprops-object-state-object).
|
64 | 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).
|
65 | renderToken | function | | Callback for custom token rendering. See full documentation in the [Rendering section](Rendering.md#rendertokenoption-objectstring-props-object-index-number).
|
66 | 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.
|
67 | selectHintOnEnter | boolean | `false` | `DEPRECATED`: Use `shouldSelect` prop on `Hint` component or `shouldSelectHint` prop on `TypeaheadInputSingle` & `TypeaheadInputMulti`. Allows selecting the hinted result by pressing enter.
|
68 | size | `'large'` \| `'lg'` \| `'small'` \| `'sm'` | | Specify the size of the input.
|
69 |
|
70 | #### Children
|
71 | In 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 | ```
|
78 | The render function receives partial internal state from the component:
|
79 | ```jsx
|
80 | <Typeahead ... >
|
81 | {(state) => (
|
82 | <div>Render me!</div>
|
83 | )}
|
84 | </Typeahead>
|
85 | ```
|
86 | This may be useful for things like customizing the loading indicator or clear button, or including an announcer for accessibility purposes.
|
87 |
|
88 | ### `<AsyncTypeahead>`
|
89 | 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.
|
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 |
|
108 | Note that this component is the same as:
|
109 | ```jsx
|
110 | import { Typeahead, withAsync } from 'react-bootstrap-typeahead';
|
111 |
|
112 | const AsyncTypeahead = withAsync(Typeahead);
|
113 | ```
|
114 |
|
115 | #### Props
|
116 | Name | Type | Default | Description
|
117 | -----|------|---------|------------
|
118 | delay | number | `200` | Delay, in milliseconds, before performing search.
|
119 | isLoading `required` | boolean | | Whether or not an asynchronous request is in progress.
|
120 | onSearch `required` | function | | Callback to perform when the search is executed, where `query` is the input string.<br><br><pre>`(query: string) => void`</pre>
|
121 | options | Array\<Object\|string\> | `[]` | Options to be passed to the typeahead. Will typically be the query results, but can also be initial default options.
|
122 | promptText | node | `'Type to search...'` | Message displayed in the menu when there is no user input.
|
123 | searchText | node | `'Searching...'` | Message to display in the menu while the request is pending.
|
124 | useCache | bool | `true` | Whether or not the component should cache query results.
|
125 |
|
126 | ### `<Highlighter>`
|
127 | Component 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
|
141 | Name | Type | Default | Description
|
142 | -----|------|---------|------------
|
143 | children `(required)` | string | | `Highlighter` expects a string as the only child.
|
144 | highlightClassName | string | `'rbt-highlight-text'` | Classname applied to the highlighted text.
|
145 | 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`.
|
146 |
|
147 | ### `<Hint>`
|
148 | The `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
|
166 | Name | Type | Default | Description
|
167 | -----|------|---------|------------
|
168 | children `(required)` | node | | `Hint` expects a single child: your input component.
|
169 | shouldSelect | function | | Callback function that determines whether the hint should be selected.<br><br><pre>`(shouldSelect: boolean, SyntheticKeyboardEvent<HTMLInputElement>) => boolean`</pre>
|
170 |
|
171 | ### `<Input>`
|
172 | Abstract `<input>` component that handles an `inputRef` prop and is used as the basis for both single- and multi-select input components.
|
173 |
|
174 | ### `<Menu>`
|
175 | Provides the markup for a Bootstrap menu, along with some extra functionality for specifying a label when there are no results.
|
176 |
|
177 | Name | Type | Default | Description
|
178 | -----|------|---------|------------
|
179 | emptyLabel | node | `'No matches found.'` | Message to display in the menu if there are no valid results.
|
180 | id `required` | string \| number | | Id value required for accessibility.
|
181 | maxHeight | string | `'300px'` | Maximum height of the dropdown menu.
|
182 |
|
183 | ### `<MenuItem>`
|
184 | 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.
|
185 |
|
186 | #### Props
|
187 | Name | Type | Default | Description
|
188 | -----|------|---------|------------
|
189 | option `(required)` | Object \| string | | The data item to be displayed.
|
190 | 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.
|
191 |
|
192 | ### `<TypeaheadInputSingle>` & `<TypeaheadInputMulti>`
|
193 | Input components that handles single- and multi-selections, respectively. In the multi-select component, selections are rendered as children.
|
194 |
|
195 | #### Props
|
196 | Name | Type | Default | Description
|
197 | -----|------|---------|------------
|
198 | disabled | boolean | `false` | Whether or not the input component is disabled.
|
199 | shouldSelectHint | 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>`
|
202 | 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.
|
203 |
|
204 | #### Props
|
205 | Name | Type | Default | Description
|
206 | -----|------|---------|------------
|
207 | labelKey `required` | string \| function | | See full documentation in the [Rendering section](Rendering.md#labelkey-string--function).
|
208 | 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}`.
|
209 | paginationText | string | `'Display additional results...'` | Prompt displayed when large data sets are paginated.
|
210 | renderMenuItemChildren | function | | Provides a hook for customized rendering of menu item contents.
|
211 | text `required` | string | | The current value of the typeahead's input.
|
212 |
|
213 | ### `<Token>`
|
214 | Individual token component, most commonly for use within `renderToken` to customize the `Token` contents.
|
215 |
|
216 | #### Props
|
217 | Name | Type | Default | Description
|
218 | -----|------|---------|------------
|
219 | option `(required)` | Object \| string | | The data item to be displayed.
|
220 | disabled | boolean | `false` | Whether the token is in a disabled state. If `true` it will not be interactive or removeable.
|
221 | href | string | | If provided, the token will be rendered with an `<a>` tag and `href` attribute.
|
222 | 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`.
|
223 | tabIndex | 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`
|
228 | The HOC used in [`AsyncTypeahead`](#asynctypeahead).
|
229 |
|
230 | ### `useItem` & `withItem`
|
231 | 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.
|
232 |
|
233 | If 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
|
236 | import { MenuItem } from 'react-bootstrap';
|
237 | import { Menu, Typeahead, useItem, withItem } from 'react-bootstrap-typeahead';
|
238 |
|
239 | const Item = withItem(MenuItem);
|
240 |
|
241 | // OR
|
242 |
|
243 | const 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`
|
259 | 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:
|
260 |
|
261 | Name | Type | Description
|
262 | -----|------|------------
|
263 | active | boolean | Whether the token is active or not. Useful for adding an "active" classname to the component for styling.
|
264 | onBlur | function | Callback invoked when the token loses focus. Should be applied to the top-level element.
|
265 | onClick | function | Callback invoked when the token is clicked. Should be applied to the top-level element.
|
266 | onFocus | function | Callback invoked when the token is focused. Should be applied to the top-level element.
|
267 | onKeyDown | function | Callback invoked when the token is focused and a key is pressed. Should be applied to the top-level element.
|
268 | 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.
|
269 | ref | 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.
|
273 | const 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
|
285 | const CustomToken = withToken(MyToken);
|
286 |
|
287 | // Hook
|
288 | const CustomToken = (props) => <MyToken {...useToken(props)} />;
|
289 | ```
|
290 | If using the hook, you can also apply it directly within your token component:
|
291 | ```jsx
|
292 | const 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`
|
309 | Hook 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
|
312 | const 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 | ```
|
327 | 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`.
|