Search code examples
javascriptreactjseditorrich-text-editorslate.js

How to pass events in the SLATEJS rich text editor


I'm trying coding follow this doc:

https://docs.slatejs.org/walkthroughs/05-executing-commands

I just wanted to make it elegant, so I tried to separate the Toolbar Button into other files. But how do I pass the event onKeydown there?

I tried the following code, but I got the result that 'editor is undefined'

Did I overlook something?

Here is a simple DEMO:

exprot function App(){
 //...others

 const [editor] = useState(() => withReact(createEditor()));
 return (
   <Slate {...props} >
     <MyToolbar {...editor} />
     //...others
   </Slate>
 );
}
function MyToolbar(editor: ReactEditor){
   return (
      <div>
        //Icon button span
        <span {...props} onMouseDown={event => {
                            event.preventDefault();
                            CustomEditor.toggleBold(editor);
                    }}></span>
      </div>
   );
}

Solution

  • Don't pass editor as a prop, use the hook useSlate() to get it:

    import { useSlate } from "slate-react";
    
    function MyToolbar() {
      const editor = useSlate();
    
      return (
        <div>
          <span
            onMouseDown={event => {
              event.preventDefault();
              CustomEditor.toggleBold(editor);
            }}
          ></span>
        </div>
      );
    }