Handle keyboard events with slate js

Julian Krispel
InstructorJulian Krispel
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 3 years ago

In this lesson we'll learn how event handling in slate js works. We'll cover the arguments passed to every event handler, how to detect a keyboard shortcut and display the currently selected text in a browser dialog.

Instructor: [00:00] We start by importing the editor component from Slate React here, initializing the value here, passing that through use state hook to manage state, and rendering the Slate editor component here.

[00:15] The editor component has many event handler props. We will use the onKeyDown prop, which is called every time the user presses a key. The onKeyDown prop is called with three arguments -- event, editor, and next.

[00:36] Always return next in your onKeyDown handler. This ensures that Slate works as expected. If event.key = C and event.metaKey is true, we know that the user has pressed the hot key for copying.

[00:59] We'll use the alert method to display a message in the browser. Pressing Command-C will display an alert. Change the single quotes of the string to backticks so we can insert a variable.

[01:13] Insert the variable editor.value.fragments.text. This will give you the currently selected text. Now, you will see the selected text in your alert.

[01:28] To summarize, all event handlers have three arguments -- event, editor, and next. Don't forget Slate expects you to return next.

egghead
egghead
~ 6 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today