-
Notifications
You must be signed in to change notification settings - Fork 933
/
Copy pathREADME.md
1159 lines (917 loc) · 42.2 KB
/
README.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# useCombobox
## The problem
You have a combobox or autocomplete dropdown in your application and you want it
to be accessible and functional. For consistency reasons you want it to follow
the [ARIA design pattern][combobox-aria-example] for a combobox. You also want
this solution to be simple to use and flexible so you can tailor it further to
your specific needs.
## This solution
`useCombobox` is a React hook that manages all the stateful logic needed to make
the combobox functional and accessible. It returns a set of props that are meant
to be called and their results destructured on the combobox's elements: its
label, toggle button, input, list and list items. The props are similar to the
ones provided by vanilla `<Downshift>` to the children render prop.
These props are called getter props and their return values are destructured as
a set of ARIA attributes and event listeners. Together with the action props and
state props, they create all the stateful logic needed for the combobox to
implement the corresponding ARIA pattern. Every functionality needed should be
provided out-of-the-box: menu toggle, item selection and up/down movement
between them, screen reader support, highlight by character keys etc.
## Types of Autocomplete
By default, our implementation and examples illustrate an autocomplete of type
_list_. This involves performing your own items filtering logic as well as
keeping the _aria_autocomplete_ value returned by the
[getInputProps](#getinputprops).
There are, in total, 3 types of autocomplete you can opt for, and these are as
follows:
- no autocomplete:
- [ARIA example][combobox-aria-example-none]
- use _aria-autocomplete="none"_ attribute to override the default value from
_getInputProps_.
- do not implement any filtering logic yourself, just render the listbox
items. Basically, take the [code example](#usage) below, remove the useState
with items, the onInputValueChange function, pass _colors_ as _items_ prop
and render the _colors_ if _isOpen_ is _true_.
- list autocomplete:
- [ARIA example][combobox-aria-example]
- just use the [example provided below](#usage) or anything equivalent.
- filtering logic inside the menu is done by the _useCombobox_ consumer.
- list and inline autocomplete:
- [ARIA example][combobox-aria-example-both]
- use _aria-autocomplete="both"_ attribute to override the default value from
_getInputProps_.
- filtering logic inside the menu is done by the _useCombobox_ consumer.
- inline autocomplete based on the highlighted item in the menu is also
performed by the consumer.
## Migration through breaking changes
The hook received breaking changes related to how it works, as well as the API,
starting with v7. They are documented here:
- [v7 migration guide][migration-guide-v7]
- [v8 migration guide][migration-guide-v8]
- [v9 migration guide][migration-guide-v9]
## Table of Contents
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
- [Usage](#usage)
- [Basic Props](#basic-props)
- [items](#items)
- [itemToString](#itemtostring)
- [onSelectedItemChange](#onselecteditemchange)
- [stateReducer](#statereducer)
- [Advanced Props](#advanced-props)
- [isItemDisabled](#isitemdisabled)
- [initialSelectedItem](#initialselecteditem)
- [initialIsOpen](#initialisopen)
- [initialHighlightedIndex](#initialhighlightedindex)
- [initialInputValue](#initialinputvalue)
- [defaultSelectedItem](#defaultselecteditem)
- [defaultIsOpen](#defaultisopen)
- [defaultHighlightedIndex](#defaulthighlightedindex)
- [defaultInputValue](#defaultinputvalue)
- [itemToKey](#itemtokey)
- [getA11yStatusMessage](#geta11ystatusmessage)
- [onHighlightedIndexChange](#onhighlightedindexchange)
- [onIsOpenChange](#onisopenchange)
- [onInputValueChange](#oninputvaluechange)
- [onStateChange](#onstatechange)
- [highlightedIndex](#highlightedindex)
- [isOpen](#isopen)
- [selectedItem](#selecteditem)
- [inputValue](#inputvalue)
- [id](#id)
- [labelId](#labelid)
- [menuId](#menuid)
- [toggleButtonId](#togglebuttonid)
- [inputId](#inputid)
- [getItemId](#getitemid)
- [environment](#environment)
- [stateChangeTypes](#statechangetypes)
- [Control Props](#control-props)
- [Returned props](#returned-props)
- [prop getters](#prop-getters)
- [actions](#actions)
- [state](#state)
- [Event Handlers](#event-handlers)
- [Default handlers](#default-handlers)
- [Customizing Handlers](#customizing-handlers)
- [Examples](#examples)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Usage
> [Try it out in the browser][sandbox-example]
```jsx
import * as React from 'react'
import {render} from 'react-dom'
import {useCombobox} from 'downshift'
const colors = [
'Black',
'Red',
'Green',
'Blue',
'Orange',
'Purple',
'Pink',
'Orchid',
'Aqua',
'Lime',
'Gray',
'Brown',
'Teal',
'Skyblue',
]
function DropdownCombobox() {
const [inputItems, setInputItems] = React.useState(colors)
const {
isOpen,
getToggleButtonProps,
getLabelProps,
getMenuProps,
getInputProps,
highlightedIndex,
getItemProps,
selectedItem,
selectItem,
} = useCombobox({
items: inputItems,
onInputValueChange: ({inputValue}) => {
setInputItems(
colors.filter(item =>
item.toLowerCase().startsWith(inputValue.toLowerCase()),
),
)
},
})
return (
<div
style={{
display: 'flex',
flexDirection: 'column',
width: 'fit-content',
justifyContent: 'center',
marginTop: 100,
alignSelf: 'center',
}}
>
<label
style={{
fontWeight: 'bolder',
color: selectedItem ? selectedItem : 'black',
}}
{...getLabelProps()}
>
Choose an element:
</label>
<div>
<input
style={{padding: '4px'}}
{...getInputProps()}
data-testid="combobox-input"
/>
<button
style={{padding: '4px 8px'}}
aria-label="toggle menu"
data-testid="combobox-toggle-button"
{...getToggleButtonProps()}
>
{isOpen ? <>↑</> : <>↓</>}
</button>
<button
style={{padding: '4px 8px'}}
aria-label="toggle menu"
data-testid="clear-button"
onClick={() => selectItem(null)}
>
✗
</button>
</div>
<ul
{...getMenuProps()}
style={{
listStyle: 'none',
width: '100%',
padding: '0',
margin: '4px 0 0 0',
}}
>
{isOpen &&
inputItems.map((item, index) => (
<li
style={{
padding: '4px',
backgroundColor: highlightedIndex === index ? '#bde4ff' : null,
}}
key={`${item}${index}`}
{...getItemProps({
item,
index,
})}
>
{item}
</li>
))}
</ul>
</div>
)
}
render(<DropdownCombobox />, document.getElementById('root'))
```
## Basic Props
This is the list of props that you should probably know about. There are some
[advanced props](#advanced-props) below as well.
### items
> `any[]` | _required_
The main difference from vanilla `Downshift` is that we pass the items we want
to render to the hook as well. Opening the menu with an item already selected
means the hook has to know in advance what items you plan to render and what is
the position of that item in the list. Consequently, there won't be any need for
two state changes: one for opening the menu and one for setting the highlighted
index, like in `Downshift`.
### itemToString
> `function(item: any)` | defaults to: `item => (item ? String(item) : '')`
If your items are stored as, say, objects instead of strings, downshift still
needs a string representation for each one. This is required for accessibility
aria-live messages (e.g., after making a selection).
**Note:** This callback _must_ include a null check: it is invoked with `null`
whenever the user abandons input via `<Esc>`.
### onSelectedItemChange
> `function(changes: object)` | optional, no useful default
Called each time the selected item was changed. Selection can be performed by
item click, Enter Key while item is highlighted or by blurring the menu while an
item is highlighted (Tab, Shift-Tab or clicking away).
- `changes`: These are the properties that actually have changed since the last
state change. This object is guaranteed to contain the `selectedItem` property
with the newly selected value. This also has a `type` property which you can
learn more about in the [`stateChangeTypes`](#statechangetypes) section. This
property will be part of the actions that can trigger a `selectedItem` change,
for example `useCombobox.stateChangeTypes.ItemClick`.
### stateReducer
> `function(state: object, actionAndChanges: object)` | optional
**🚨 This is a really handy power feature 🚨**
This function will be called each time `useCombobox` sets its internal state (or
calls your `onStateChange` handler for control props). It allows you to modify
the state change that will take place which can give you fine grain control over
how the component interacts with user updates. It gives you the current state
and the state that will be set, and you return the state that you want to set.
- `state`: The full current state of downshift.
- `actionAndChanges`: Object that contains the action `type`, props needed to
return a new state based on that type and the changes suggested by the
Downshift default reducer. About the `type` property you can learn more about
in the [`stateChangeTypes`](#statechangetypes) section.
```javascript
import {useCombobox} from 'downshift'
import {items} from './utils'
const {getMenuProps, getItemProps, ...rest} = useCombobox({
items,
stateReducer,
})
function stateReducer(state, actionAndChanges) {
const {type, changes} = actionAndChanges
// this prevents the menu from being closed when the user selects an item with 'Enter' or mouse
switch (type) {
case useCombobox.stateChangeTypes.InputKeyDownEnter:
case useCombobox.stateChangeTypes.ItemClick:
return {
...changes, // default Downshift new state changes on item selection.
isOpen: state.isOpen, // but keep menu open.
highlightedIndex: state.highlightedIndex, // with the item highlighted.
}
default:
return changes // otherwise business as usual.
}
}
```
> NOTE: This is only called when state actually changes. You should not attempt
> use this to handle events. If you wish to handle events, put your event
> handlers directly on the elements (make sure to use the prop getters though!
> For example `<button onBlur={handleBlur} />` should be
> `<button {...getToggleButtonProps({onBlur: handleBlur})} />`). Also, your
> reducer function should be "pure." This means it should do nothing other than
> return the state changes you want to have happen.
## Advanced Props
### isItemDisabled
> `function(item: any, index: number)` | defaults to: `(_item, _index) => false`
If an item needs to be marked as disabled, this function needs to return `true`
for that item. Disabled items will be skipped from keyboard navigation, will not
be selected and will be marked as disabled for screen readers.
### initialSelectedItem
> `any` | defaults to `null`
Pass an item that should be selected when downshift is initialized.
### initialIsOpen
> `boolean` | defaults to `false`
Pass a boolean that sets the open state of the menu when downshift is
initialized.
### initialHighlightedIndex
> `number` | defaults to `-1`
Pass a number that sets the index of the highlighted item when downshift is
initialized.
### initialInputValue
> `string` | defaults to `''`
Pass a string that sets the content of the input when downshift is initialized.
### defaultSelectedItem
> `any` | defaults to `null`
Pass an item that should be selected when downshift is reset.
### defaultIsOpen
> `boolean` | defaults to `false`
Pass a boolean that sets the open state of the menu when downshift is reset or
when an item is selected.
### defaultHighlightedIndex
> `number` | defaults to `-1`
Pass a number that sets the index of the highlighted item when downshift is
reset or when an item is selected.
### defaultInputValue
> `string` | defaults to `''`
Pass a string that sets the content of the input when downshift is reset or when
an item is selected.
### itemToKey
> `function(item: any)` | defaults to: `item => item`
Used to determine the uniqueness of an item when searching for the item or
comparing the item with another. Returns the item itself, by default, so the
comparing/searching is done internally via referential equality.
If using items as objects and their reference will change during use, you can
use the function to generate a unique key for each item, such as an `id` prop.
```js
function itemToKey(item) {
return item.id
}
```
> This deprecates the "selectedItemChanged" prop. If you are using the prop
> already, make sure you change to "itemToKey" as the former is removed in v9. A
> migration example:
```js
// initial items.
const items = [
{id: 1, value: 'Apples'},
{id: 2, value: 'Oranges'},
]
// the same items but with different references, for any reason.
const newItems = [
{id: 1, value: 'Apples'},
{id: 2, value: 'Oranges'},
]
// previously, if you probably had something like this.
function selectedItemChanged(item1, item2) {
return item1.id === item2.id
}
// moving forward, switch to this one.
function itemToKey(item) {
return item.id
// and we will do the comparison like: const isChanged = itemToKey(prevSelectedItem) !== itemToKey(nextSelectedItem)
}
```
### getA11yStatusMessage
> `function({/* see below */})` | default messages provided in English
This function is passed as props to a status updating function nested within
that allows you to create your own ARIA statuses. It is called when the state
changes: `selectedItem`, `highlightedIndex`, `inputValue` or `isOpen`.
There is no default function provided anymore since v9, so if there's no prop
passed, no aria live status message is created. An implementation that resembles
the previous default is written below, should you want to keep pre v9 behaviour.
We don't provide this as a default anymore since we consider that screen readers
have been significantly improved and they can convey information about items
count, possible actions and highlighted items only from the HTML markup, without
the need for aria-live regions.
```js
function getA11yStatusMessage(state) {
if (!state.isOpen) {
return ''
}
// you need to get resultCount and previousResultCount yourself now, since we don't pass them as arguments anymore
const resultCount = items.length
const previousResultCount = previousResultCountRef.current
if (!resultCount) {
return 'No results are available.'
}
if (resultCount !== previousResultCount) {
return `${resultCount} result${
resultCount === 1 ? ' is' : 's are'
} available, use up and down arrow keys to navigate. Press Enter key to select.`
}
return ''
}
```
### onHighlightedIndexChange
> `function(changes: object)` | optional, no useful default
Called each time the highlighted item was changed. Items can be highlighted
while hovering the mouse over them or by keyboard keys such as Up Arrow, Down
Arrow, Home and End. Items can also be highlighted by hitting character keys
that are part of their starting string equivalent.
- `changes`: These are the properties that actually have changed since the last
state change. This object is guaranteed to contain the `highlightedIndex`
property with the new value. This also has a `type` property which you can
learn more about in the [`stateChangeTypes`](#statechangetypes) section. This
property will be part of the actions that can trigger a `highlightedIndex`
change, for example `useCombobox.stateChangeTypes.InputKeyDownArrowUp`.
### onIsOpenChange
> `function(changes: object)` | optional, no useful default
Called each time the menu is open or closed. Menu can be open by toggle button
click, Enter, Space, Up Arrow or Down Arrow keys. Can be closed by selecting an
item, blur (Tab, Shift-Tab or clicking outside), clicking the toggle button
again or hitting Escape key.
- `changes`: These are the properties that actually have changed since the last
state change. This object is guaranteed to contain the `isOpen` property with
the new value. This also has a `type` property which you can learn more about
in the [`stateChangeTypes`](#statechangetypes) section. This property will be
part of the actions that can trigger a `isOpen` change, for example
`useCombobox.stateChangeTypes.ToggleButtonClick`.
### onInputValueChange
> `function(changes: object)` | optional, no useful default
Called each time the value in the input text changes. The input value should
change like any input of type text, at any character key press, `Space`,
`Backspace`, `Escape` etc.
- `changes`: These are the properties that actually have changed since the last
state change. This object is guaranteed to contain the `inputValue` property
with the new value. This also has a `type` property which you can learn more
about in the [`stateChangeTypes`](#statechangetypes) section. This property
will be part of the actions that can trigger a `inputValue` change, for
example `useCombobox.stateChangeTypes.InputChange`.
### onStateChange
> `function(changes: object)` | optional, no useful default
This function is called anytime the internal state changes. This can be useful
if you're using downshift as a "controlled" component, where you manage some or
all of the state (e.g., isOpen, selectedItem, highlightedIndex, etc) and then
pass it as props, rather than letting downshift control all its state itself.
- `changes`: These are the properties that actually have changed since the last
state change. This also has a `type` property which you can learn more about
in the [`stateChangeTypes`](#statechangetypes) section.
> Tip: This function will be called any time _any_ state is changed. The best
> way to determine whether any particular state was changed, you can use
> `changes.hasOwnProperty('propName')` or use the `on[statePropKey]Change` props
> described above.
> NOTE: This is only called when state actually changes. You should not attempt
> to use this to handle events. If you wish handle events, put your event
> handlers directly on the elements (make sure to use the prop getters though!
> For example: `<button onBlur={handleBlur} />` should be
> `<button {...getToggleButtonProps({onBlur: handleBlur})} />`).
### highlightedIndex
> `number` | **control prop** (read more about this in
> [the Control Props section](#control-props))
The index of the item that should be highlighted when menu is open.
### isOpen
> `boolean` | **control prop** (read more about this in
> [the Control Props section](#control-props))
The open state of the menu.
### selectedItem
> `any` | **control prop** (read more about this in
> [the Control Props section](#control-props))
The item that should be selected.
### inputValue
> `string` | **control prop** (read more about this in
> [the Control Props section](#control-props))
The value to be displayed in the text input.
🚨 Important 🚨
If you use `onInputValueChange`, `onStateChange` or anything similar in order to
update a state variable that will end up controlling `inputValue`, you will
encounter a
[cursor jump issue](https://github.com/downshift-js/downshift/issues/1108).
There's no way to properly fix this in our current `React.useReducer` setup, so
in order to work around the issue, consider the change below.
```jsx
const [value, setValue] = useState('')
const {getInputProps} = useCombobox({
items: [],
inputValue: value,
// change this:
onInputValueChange: ({inputValue}) => {
setValue(inputValue)
},
})
return (
<input
{...getInputProps({
// to this:
onChange: e => {
setValue(e.target.value)
},
})}
/>
)
```
### id
> `string` | defaults to a generated ID
Used to generate the first part of the `Downshift` id on the elements. You can
override this `id` with one of your own, provided as a prop, or you can override
the `id` for each element altogether using the props below.
### labelId
> `string` | defaults to a generated ID
Used for `aria` attributes and the `id` prop of the element (`label`) you use
[`getLabelProps`](#getlabelprops) with.
### menuId
> `string` | defaults to a generated ID
Used for `aria` attributes and the `id` prop of the element (`ul`) you use
[`getMenuProps`](#getmenuprops) with.
### toggleButtonId
> `string` | defaults to a generated ID
Used for `aria` attributes and the `id` prop of the element (`button`) you use
[`getToggleButtonProps`](#gettogglebuttonprops) with.
### inputId
> `string` | defaults to a generated ID
Used for `aria` attributes and the `id` prop of the element (`input`) you use
[`getInputProps`](#getmenuprops) with.
### getItemId
> `function(index)` | defaults to a function that generates an ID based on the
> index
Used for `aria` attributes and the `id` prop of the element (`li`) you use
[`getItemProps`](#getitemprops) with.
### environment
> `window` | defaults to `window`
This prop is only useful if you're rendering downshift within a different
`window` context from where your JavaScript is running; for example, an iframe
or a shadow-root. If the given context is lacking `document` and/or
`add|removeEventListener` on its prototype (as is the case for a shadow-root)
then you will need to pass in a custom object that is able to provide
[access to these properties](https://gist.github.com/Rendez/1dd55882e9b850dd3990feefc9d6e177)
for downshift.
## stateChangeTypes
There are a few props that expose changes to state
([`onStateChange`](#onstatechange) and [`stateReducer`](#statereducer)). For you
to make the most of these APIs, it's important for you to understand why state
is being changed. To accomplish this, there's a `type` property on the `changes`
object you get. This `type` corresponds to a `stateChangeTypes` property.
The list of all possible values this `type` property can take is defined in
[this file][state-change-file] and is as follows:
- `useCombobox.stateChangeTypes.InputKeyDownArrowDown`
- `useCombobox.stateChangeTypes.InputKeyDownArrowUp`
- `useCombobox.stateChangeTypes.InputKeyDownEscape`
- `useCombobox.stateChangeTypes.InputKeyDownHome`
- `useCombobox.stateChangeTypes.InputKeyDownEnd`
- `useCombobox.stateChangeTypes.InputKeyDownPageUp`
- `useCombobox.stateChangeTypes.InputKeyDownPadeDown`
- `useCombobox.stateChangeTypes.InputKeyDownEnter`
- `useCombobox.stateChangeTypes.InputChange`
- `useCombobox.stateChangeTypes.InputClick`
- `useCombobox.stateChangeTypes.InputBlur`
- `useCombobox.stateChangeTypes.MenuMouseLeave`
- `useCombobox.stateChangeTypes.ItemMouseMove`
- `useCombobox.stateChangeTypes.ItemClick`
- `useCombobox.stateChangeTypes.ToggleButtonClick`
- `useCombobox.stateChangeTypes.FunctionToggleMenu`
- `useCombobox.stateChangeTypes.FunctionOpenMenu`
- `useCombobox.stateChangeTypes.FunctionCloseMenu`
- `useCombobox.stateChangeTypes.FunctionSetHighlightedIndex`
- `useCombobox.stateChangeTypes.FunctionSelectItem`
- `useCombobox.stateChangeTypes.FunctionSetInputValue`
- `useCombobox.stateChangeTypes.FunctionReset`
See [`stateReducer`](#statereducer) for a concrete example on how to use the
`type` property.
## Control Props
Downshift manages its own state internally and calls your
`onSelectedItemChange`, `onIsOpenChange`, `onHighlightedIndexChange`,
`onInputChange` and `onStateChange` handlers with any relevant changes. The
state that downshift manages includes: `isOpen`, `selectedItem`, `inputValue`
and `highlightedIndex`. Returned action function (read more below) can be used
to manipulate this state and can likely support many of your use cases.
However, if more control is needed, you can pass any of these pieces of state as
a prop (as indicated above) and that state becomes controlled. As soon as
`this.props[statePropKey] !== undefined`, internally, `downshift` will determine
its state based on your prop's value rather than its own internal state. You
will be required to keep the state up to date (this is where `onStateChange`
comes in really handy), but you can also control the state from anywhere, be
that state from other components, `redux`, `react-router`, or anywhere else.
> Note: This is very similar to how normal controlled components work elsewhere
> in react (like `<input />`). If you want to learn more about this concept, you
> can learn about that from the [Advanced React Component Patterns
> course][advanced-react-component-patterns-course]
## Returned props
You use the hook like so:
```javascript
import {useCombobox} from 'downshift'
import {items} from './utils'
const {getInputProps, reset, ...rest} = useCombobox({
items,
...otherProps,
})
return (
<div>
<input {...getInputProps()} />
{/* render the menu and items */}
{/* render a button that resets the select to defaults */}
<button
onClick={() => {
reset()
}}
>
Reset
</button>
</div>
)
```
> NOTE: In this example we used both a getter prop `getInputProps` and an action
> prop `reset`. The properties of `useCombobox` can be split into three
> categories as indicated below:
### prop getters
> See [the blog post about prop getters][blog-post-prop-getters]
> NOTE: These prop-getters provide `aria-` attributes which are very important
> to your component being accessible. It's recommended that you utilize these
> functions and apply the props they give you to your components.
These functions are used to apply props to the elements that you render. This
gives you maximum flexibility to render what, when, and wherever you like. You
call these on the element in question, for example on the toggle button:
`<button {...getToggleButtonProps()}`. It's advisable to pass all your props to
that function rather than applying them on the element yourself to avoid your
props being overridden (or overriding the props returned). For example:
`getToggleButtonProps({onKeyDown(event) {console.log(event)}})`.
<!-- This table was generated via http://www.tablesgenerator.com/markdown_tables -->
| property | type | description |
| ---------------------- | -------------- | ---------------------------------------------------------------------------------------------- |
| `getToggleButtonProps` | `function({})` | returns the props you should apply to any menu toggle button element you render. |
| `getItemProps` | `function({})` | returns the props you should apply to any menu item elements you render. |
| `getLabelProps` | `function({})` | returns the props you should apply to the `label` element that you render. |
| `getMenuProps` | `function({})` | returns the props you should apply to the `ul` element (or root of your menu) that you render. |
| `getInputProps` | `function({})` | returns the props you should apply to the `input` element that you render. |
#### `getLabelProps`
This method should be applied to the `label` you render. It will generate an
`id` that will be used to label the toggle button and the menu.
There are no required properties for this method.
> Note: For accessibility purposes, calling this method is highly recommended.
#### `getMenuProps`
This method should be applied to the element which contains your list of items.
Typically, this will be a `<div>` or a `<ul>` that surrounds a `map` expression.
This handles the proper ARIA roles and attributes.
Optional properties:
- `refKey`: if you're rendering a composite component, that component will need
to accept a prop which it forwards to the root DOM element. Commonly, folks
call this `innerRef`. So you'd call: `getMenuProps({refKey: 'innerRef'})` and
your composite component would forward like: `<ul ref={props.innerRef} />`.
However, if you are just rendering a primitive component like `<div>`, there
is no need to specify this property. It defaults to `ref`.
Please keep in mind that menus, for accessiblity purposes, should always be
rendered, regardless of whether you hide it or not. Otherwise, `getMenuProps`
may throw error if you unmount and remount the menu.
- `aria-label`: By default the menu will add an `aria-labelledby` that refers to
the `<label>` rendered with `getLabelProps`. However, if you provide
`aria-label` to give a more specific label that describes the options
available, then `aria-labelledby` will not be provided and screen readers can
use your `aria-label` instead.
In some cases, you might want to completely bypass the `refKey` check. Then you
can provide the object `{suppressRefError : true}` as the second argument to
`getMenuProps`. **Please use it with extreme care and only if you are absolutely
sure that the ref is correctly forwarded otherwise `useCombobox` will
unexpectedly fail.**
```jsx
const {getMenuProps} = useCombobox({items})
const ui = (
<ul {...getMenuProps()}>
{!isOpen
? null
: items.map((item, index) => (
<li {...getItemProps({item, index, key: item.id})}>{item.name}</li>
))}
</ul>
)
```
> Note that for accessibility reasons it's best if you always render this
> element whether or not downshift is in an `isOpen` state.
#### `getItemProps`
The props returned from calling this function should be applied to any menu
items you render.
**This is an impure function**, so it should only be called when you will
actually be applying the props to an item.
<details>
<summary>What do you mean by impure function?</summary>
Basically just don't do this:
```jsx
items.map((item, index) => {
const props = getItemProps({item, index}) // we're calling it here
if (!shouldRenderItem(item)) {
return null // but we're not using props, and downshift thinks we are...
}
return <div {...props} />
})
```
Instead, you could do this:
```jsx
items.filter(shouldRenderItem).map(item => <div {...getItemProps({item})} />)
```
</details>
Required properties:
The main difference from vanilla `Downshift` is that we require the items as
props before rendering. The reason is to open the menu with items already
highlighted, and we need to know the items before the actual render. It is still
required to pass either `item` or `index` to `getItemProps`.
- `item`: this is the item data that will be selected when the user selects a
particular item.
- `index`: This is how `downshift` keeps track of your item when updating the
`highlightedIndex` as the user keys around. By default, `downshift` will
assume the `index` is the order in which you're calling `getItemProps`. This
is often good enough, but if you find odd behavior, try setting this
explicitly. It's probably best to be explicit about `index` when using a
windowing library like `react-virtualized`.
Optional properties:
- `ref`: if you need to access the item element via a ref object, you'd call the
function like this: `getItemProps({ref: yourItemRef})`. As a result, the item
element will receive a composed `ref` property, which guarantees that both
your code and `useCombobox` use the same correct reference to the element.
- `refKey`: if you're rendering a composite component, that component will need
to accept a prop which it forwards to the root DOM element. Commonly, folks
call this `innerRef`. So you'd call: `getItemProps({refKey: 'innerRef'})` and
your composite component would forward like: `<li ref={props.innerRef} />`.
However, if you are just rendering a primitive component like `<div>`, there
is no need to specify this property. It defaults to `ref`.
#### `getToggleButtonProps`
Call this and apply the returned props to a `button`. It allows you to toggle
the `Menu` component.
Optional properties:
- `ref`: if you need to access the button element via a ref object, you'd call
the function like this: `getToggleButton({ref: yourButtonRef})`. As a result,
the button element will receive a composed `ref` property, which guarantees
that both your code and `useCombobox` use the same correct reference to the
element.
- `refKey`: if you're rendering a composite component, that component will need
to accept a prop which it forwards to the root DOM element. Commonly, folks
call this `innerRef`. So you'd call: `getToggleButton({refKey: 'innerRef'})`
and your composite component would forward like:
`<button ref={props.innerRef} />`. However, if you are just rendering a
primitive component like `<div>`, there is no need to specify this property.
It defaults to `ref`.
- `disabled`: If this is set to `true`, then all of the downshift button event
handlers will be omitted (it won't toggle the menu when clicked).
```jsx
const {getToggleButtonProps} = useCombobox({items})
const myButton = (
<button {...getToggleButtonProps()}>Click me</button>
{/* menu and items */}
)
```
#### `getInputProps`
This method should be applied to the `input` you render. It is recommended that
you pass all props as an object to this method which will compose together any
of the event handlers you need to apply to the `input` while preserving the ones
that `downshift` needs to apply to make the `input` behave.
There are no required properties for this method.
Optional properties:
- `disabled`: If this is set to true, then no event handlers will be returned
from `getInputProps` and a `disabled` prop will be returned (effectively
disabling the input).
- `ref`: if you need to access the input element via a ref object, you'd call
the function like this: `getInputProps({ref: yourInputRef})`. As a result, the
input element will receive a composed `ref` property, which guarantees that
both your code and `useCombobox` use the same correct reference to the
element.
- `refKey`: if you're rendering a composite component, that component will need
to accept a prop which it forwards to the root DOM element. Commonly, folks
call this `innerRef`. So you'd call: `getInputProps({refKey: 'innerRef'})` and
your composite component would forward like: `<input ref={props.innerRef} />`.
However, if you are just rendering a primitive component like `<div>`, there
is no need to specify this property. It defaults to `ref`.
- `aria-label`: By default the input will add an `aria-labelledby` that refers
to the `<label>` rendered with `getLabelProps`. However, if you provide
`aria-label` to give a more specific label that describes the options
available, then `aria-labelledby` will not be provided and screen readers can
use your `aria-label` instead.
In some cases, you might want to completely bypass the `refKey` check. Then you
can provide the object `{suppressRefError : true}` as the second argument to
`getInput`. **Please use it with extreme care and only if you are absolutely
sure that the ref is correctly forwarded otherwise `useCombobox` will
unexpectedly fail.**
### actions
These are functions you can call to change the state of the downshift
`useCombobox` hook.
<!-- This table was generated via http://www.tablesgenerator.com/markdown_tables -->
| property | type | description |
| --------------------- | ------------------------- | ----------------------------------------------------- |
| `closeMenu` | `function()` | closes the menu |
| `openMenu` | `function()` | opens the menu |
| `selectItem` | `function(item: any)` | selects the given item |
| `setHighlightedIndex` | `function(index: number)` | call to set a new highlighted index |
| `setInputValue` | `function(value: string)` | call to set a new value in the input |
| `toggleMenu` | `function()` | toggle the menu open state |
| `reset` | `function()` | this resets downshift's state to a reasonable default |
### state
These are values that represent the current state of the downshift component.
<!-- This table was generated via http://www.tablesgenerator.com/markdown_tables -->
| property | type | description |