2

For the life of me, I can't figure out how to clear all of the text in an Editor component from slate.js.

I have tried:

Transforms.delete(editor, {}); -> doesn't do anything

editor.deleteBackward("line"); -> only deletes one line, not all

I have also tried manually rerendering the editor component and that unfortunately doesn't update it to its initial state :(

I have been tearing through the slate js docs and can't find anything anywhere! If anyone has any ideas, would be very happy.

This is how editor is implemented:

  const editor = useMemo(() => withHistory(withReact(createEditor())), []);

 <Editable
      key={stateKey}
      onKeyDown={(event: any) => handleKeyDown(event)}
      style={{ overflowWrap: "anywhere", width: "100%" }}
      onPaste={(e) => {
        if (e.clipboardData) {
          if (e.clipboardData.files.length > 0) {
            setFiles([...files, ...Array.from(e.clipboardData.files)]);
            e.preventDefault();
          }
        }
      }}
      decorate={decorate}
      renderLeaf={renderLeaf}
      placeholder="What's happening?"
    />

2 Answers2

6

You can mutate editor.children and set it to an "empty" value.

const editor = useMemo(() => withHistory(withReact(createEditor())), []);

editor.children = [
    {
        type: "paragraph",
        children: [{ text: "" }]
    }
];

Note: Slate needs a minimum of an array with one empty text node to render correctly.

UPDATE Feb 2023: You will also need to reset the selection and history objects within the editor.

const point = { path: [0, 0], offset: 0 }
editor.selection = { anchor: point, focus: point };
editor.history = { redos: [], undos: [] }; 
editor.children = [{
    type: "paragraph",
    children: [{ text: "" }]
}];
rantao
  • 1,621
  • 4
  • 14
  • 34
  • `Error: Cannot resolve a DOM point from Slate point: {"path":[0,0],"offset":15}` Is what happens, any thoughts? – Steven Schwartz Oct 17 '22 at 22:55
  • This causes a error to be thrown `Uncaught Error: Cannot find a descendant at path [0,0,0] in node: {"children":[{"type":"paragraph","children":[{"text":""}]}],"operations":[],"selection":{"anchor":{"path":[0,0,0],"offset":3},"focus":{"path":[0,0,0],"offset":3}},"marks":null}`. – Mr.Grease Feb 27 '23 at 21:02
  • @Mr.Grease see my latest update. – rantao Feb 28 '23 at 00:20
2

You can use

   import { Transforms } from "slate";

   // useref
   const editorRef = useRef()
   if (!editorRef.current) editorRef.current = withHistory(withReact(createEditor()))
   const editor = editorRef.current

   const reset = () =>{
      // loop delete all
      editor.children.map(item => {
        Transforms.delete(editor, { at: [0] })
      })
    
      // reset init 
      editor.children = [
      {
         type: "p",
         children: [{ text: "" }]
      }];
   }
   
somkid
  • 21
  • 1
  • 3