UNPKG

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