Draft-js: Can't detect Shift+Enter on Keybinding.

Created on 6 May 2016  路  3Comments  路  Source: facebook/draft-js

Hello, I'm new to Draft-js and it seems that the keybinding function can't detect the shft+enter thing.

function myKeyBindingFn(e) {

    if (e.keyCode === 13 && e.shiftKey) {
        return 'shift-enter';
    } else if (e.keyCode === 13) {
    return 'enter-only';
    }

    return getDefaultKeyBinding(e);
}

on my class

    handleKeyCommand(command) {
    console.log(command);
    }

...

<Editor editorState={this.state.editorState} onChange={this.onChange} handleKeyCommand={this.handleKeyCommand} keyBindingFn={myKeyBindingFn}  />

The above code can't detect the enter key,

And if I use the handleReturn it only reads when I press enter, or.. Am I missing something? thanks!

question

Most helpful comment

I solved this by checking the alt key inside enter-key if-statement.

function myKeyBindingFn(e: SyntheticKeyboardEvent): string {
  if (e.keyCode === 13 /* `Enter` key */) {
    if (e.nativeEvent.shiftKey) {
        // Alt + Enter
    } else {
        // Enter
    }
  }
  return getDefaultKeyBinding(e);
}

All 3 comments

Most of the time the browser interprets shift + enter as CRLF inside the inputs that would normally trigger an action or save on pressing enter. Seems to me you might look into that. Maybe there is some higher level binding that is not allowing it to happen.

If you use handleReturn, you will be able to observe shift+return. The return key event is prevented, though, so you will need to perform the text insertion for the soft newline yourself. (See https://github.com/facebook/draft-js/blob/master/src/model/modifier/RichTextEditorUtil.js#L81, which can do this for you.)

If you choose to use a key command for this instead, you will need to make sure that your handleKeyCommand can consume the command name that you return.

I solved this by checking the alt key inside enter-key if-statement.

function myKeyBindingFn(e: SyntheticKeyboardEvent): string {
  if (e.keyCode === 13 /* `Enter` key */) {
    if (e.nativeEvent.shiftKey) {
        // Alt + Enter
    } else {
        // Enter
    }
  }
  return getDefaultKeyBinding(e);
}
Was this page helpful?
0 / 5 - 0 ratings