1

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>
  );
}
kar
  • 4,791
  • 12
  • 49
  • 74

2 Answers2

2

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

0

I had this issue too while using a stringified Lexical node tree. For context my stringified content came from the Lexical Playground with their "export" feature...

It wraps what's needed into a {editorState:{...}}. It seems it's not the standard way for the LexicalComposer to be initialized, so after removing this wrapper to directly get {root:{...}} it works :)

Thomas Ramé
  • 438
  • 4
  • 10