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

    Style rich text with keyboard shortcuts using slate js

    Julian KrispelJulian Krispel
    reactReact

    Using the onKeyDown event handler, we'll learn how to toggle styles (in slate, styles are called mark's) for your currently selected text when certain keys are pressed. We'll also use the renderMark method to render these styles.

    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
    Transcript

    Transcript

    Instructor: Our starting point is a basic React component. Here, we import the editor component from Slate React, and here, we render it. Our value is managed with the useState hook, and we use the onChange prop to update that value.

    First, we will define the onKeydown prop. It has three arguments, event, editor, and next. Always return next for every event handler. Now, we want to format the selected text when the user has pressed the command key together with B. That will be the key combination for bold.

    If event key equals B, and event meta key equals true, we use the editor toggle mark method to add a mark for the currently-selected text. We won't actually see these marks unless we define the renderMark prop.

    As usual, the method has three arguments, props, editor, and next. Always return next. Now, we want to check if the current mark is of type bold, and if that's the case, we surround the children prop with the strong HTML element.

    Select some text in your editor, press command-B, and watch the text style change. Press command-B again, and the style will revert to its original. We have used the onKeydown method that gets fired whenever a key is pressed down.

    We check if the user has pressed B plus the command key, and then toggle the mark bold. Always return next in your method props. Finally, we use the renderMark prop to check if the current mark is bold, and then wrap props.children in a strong tag.

    Discuss

    Discuss