Search code examples
javascriptnext.jslexicaljs

Set initial state for editor


I am using lexical and want to set initial text for the editor.

For now, I am just trying to hardcode the initial text. Turns out I can't just pass a String.

It needs to be in JSON format.

Thus I am passing in the following instead.

'{"text":"sample text"}'

But it throws following error:

TypeError: Cannot read properties of undefined (reading 'type')

What am I doing wrong?

function Placeholder() {
  return <div className="editor-placeholder">Enter some rich text...</div>;
}

const editorConfig = {

  // This is how I am trying to set initial value.
  // no errors if I remove this. I need this cos I need to set initial value.
  editorState: '{"text":"sample text"}',

  // other params
};

export default function Editor() {

  return (
    <LexicalComposer initialConfig={editorConfig}>
      <div className="editor-container">
        <ToolbarPlugin />
        <div className="editor-inner">
          <RichTextPlugin
            contentEditable={<ContentEditable className="editor-input" />}
            placeholder={<Placeholder />}
          />
          {/* other login components */}
        </div>
      </div>
    </LexicalComposer>
  );
}

Solution

  • I had the same problem. Apparently editorState can be set to a function:

    const editorConfig = {
      editorState: () => {
        const root = $getRoot();
        root.clear();
        const p = $createParagraphNode();
        p.append($createTextNode("preloaded node"));
        root.append(p);
      }
    };
    

    I found this solution in Lexical Playground sources: https://github.com/facebook/lexical/blob/main/packages/lexical-playground/src/App.tsx

    Here is a simplified example: https://codesandbox.io/s/lexical-plain-playground-72pwge?file=/src/Editor.js:683-960