Style rich text with keyboard shortcuts using slate js
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.
Duration
2 min
Access
Free
Transcript
Available
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.
Video 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.