Draft's Editor component takes an optional prop called keyBindingFn
. If you assign a function to it, that function will receive all keyDown
events. In theory, you could do whatever you want in this function, but its responsibility is really to return a command, of type string, that should be executed for a specific key (or combination of keys). It could look something like this:
function keyBindingFn(e) {
if (e.key === 'Delete') {
return 'delete-me' // name this whatever you want
}
// This wasn't the delete key, so we return Draft's default command for this key
return Draft.getDefaultKeyBinding(e)
}
The Editor
component also takes another optional prop called handleKeyCommand
. If a function is assigned to this, it will receive all commands executed in the editor. This means that it, if you used my example above, would receive the command 'delete-me', whenever the delete key is pressed. This is the place to handle that command.
function handleKeyCommand(command) {
if (command === 'delete-me') {
// Do what you want to here, then tell Draft that we've taken care of this command
return 'handled'
}
// This wasn't the 'delete-me' command, so we want Draft to handle it instead.
// We do this by telling Draft we haven't handled it.
return 'not-handled'
}
To clarify, you pass these functions to the Editor component like this:
<Editor
keyBindingFn={keyBindingFn}
handleKeyCommand={handleKeyCommand}
... // other props
/>
You can read more about it in the Draft docs.