How to clear all text in Slate.JS editor

2.1k Views Asked by At

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

There are 2 best solutions below

3
rantao On

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: "" }]
}];
0
somkid On

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: "" }]
      }];
   }