Slate: e.preventDefault() does not seem to affect 'enter' and 'backspace' keys

Created on 30 Oct 2017  路  4Comments  路  Source: ianstormtaylor/slate

Do you want to request a feature or report a bug?

bug

What's the current behavior?

event.preventDefault() doesn't seem to affect the 'enter' and 'backspace' keys.

This was raised in #1179, but that issue was closed as a usage question. It could be that this is the intended behavior, but I couldn't find any mention of it in the docs, so I thought I would raise it again here.

_see this fiddle:_
https://jsfiddle.net/blaqbern/2zokvrvt/283/

_Some context:_
I'm capturing the enter key event when the current block is part of a list and applying the following change:

// parentList is the closest parent with type 'ordered-list' or 'unordered-list'
// newListItem is a new node (created with Block.create) of type 'list-item'
change
  .insertNodeByKey(
    parenList.key,
    desiredIndex,
    newListItem
  )
  .collapseToStartOfNextBlock()

This is applied as expected, but then afterwards the default behavior for the enter key is applied and I end up with an empty default node before my inserted list item node:

slate_preventdefault_enter_key

What's the expected behavior?

When calling event.preventDefault() in onKeyDown, no new line is created on 'enter'.

question

All 4 comments

Hey @blaqbern, good question.

This is actually working as expected, but I understand why it's confusing. The event.preventDefault() is actually reserved for preventing the native browser behavior, and isn't something Slate checks for. The way enter is handled by Slate is done in it's core "after" plugin, which runs after all other userland plugins.

In this case, your changes are being applied, and then the editor is continuing through the plugins stack, comes to the after plugin, and breaks the block in two.

To prevent it from continuing through the stack, you need to return a non-null value from your change handler鈥擨'd recommend doing return false for clarity. (We might enforce it to be false instead of just non-null in the future.)

@ianstormtaylor Thanks so much for the _very_ quick response! This solved it for me!

@ianstormtaylor does this also apply to the tab key? Want to keep focus on the editor after a tab keypress.

Trying this with no success.

onKeyDown = (e: SyntheticKeyboardEvent<*>, change: Change) => {
  if (e.keyCode === 9) {
    e.preventDefault();
    e.stopPropagation();
    return false;
  }
}

Nevermind! Figured it out. Was adding a node and needed to specify cursor movement

Was this page helpful?
0 / 5 - 0 ratings

Related issues

JSH3R0 picture JSH3R0  路  3Comments

vdms picture vdms  路  3Comments

ezakto picture ezakto  路  3Comments

Slapbox picture Slapbox  路  3Comments

markolofsen picture markolofsen  路  3Comments