Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Handle keyboard events with slate js

    Julian KrispelJulian Krispel
    reactReact

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: 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.

    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.

    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.

    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.

    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.

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