How do I access key value in stateReducer
I need to make special logic for pressing the backspace key inside of the state reducer and would like a clean way to access that inside of the stateReducer property. How can I do this?
Not sure it's a good place to apply your logic, stateReducer will only give you events such as Downshift.stateChangeTypes.changeInput and you need to figure it out if backspace was pressed (comparing previous and next inputValue).
You can add a custom onKeyDown to getInputProps and do your backspace logic there if possible, since there you will have access to the event and can get the key from it.
Otherwise the first option if you really need previous and next state available to you. What do you actually need?
I want to return changes if a key is pressed when the state (inputValue) is less than 6 characters long. If it's longer than that, I want to return the state. But if it's 6 characters long and the backspace is pressed, I want to return the changes so that it reflects the deletion of the last character.
I thought of one way to do this (typescript, thus the bangs): const pressedBackspace = state.inputValue!.length - changes.inputValue!.length === 1
don't we expose typings for DownshiftState ?
Edit:
stateReducer?: (
state: DownshiftState<Item>,
changes: StateChangeOptions<Item>,
) => Partial<StateChangeOptions<Item>>
Edit 2:
Why not just compare changes.inputValue.length to 6 and return inputValue as changes.inputValue only if it's less or equal than that? Otherwise just return state.inputValue as inputValue.
I don't have those typings. I get a typescript error saying those are undefined. Am I missing an import somewhere? Downshift v3.3.4
Comparison as you said works too.
Import them like this
import Downshift, {
DownshiftState,
StateChangeOptions,
GetMenuPropsOptions,
GetPropsCommonOptions,
GetInputPropsOptions,
GetToggleButtonPropsOptions,
GetItemPropsOptions,
... anything else you need
} from 'downshift'