Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With Lexical, how do I set default initial text?

Tags:

lexicaljs

With the Lexical text editor framework, what's the easiest way to initialize the editor in React with a default text string?

I could, for instance, create an instance, manually save the JSON state, and then copy that JSON blob to my code, to set as initialEditorState to PlainTextPlugin, but this seems like I have to be missing something.

Thanks 🙏

like image 697
fisch2 Avatar asked Nov 16 '25 06:11

fisch2


1 Answers

Your intuition is correct. Avoid touching the EditorState directly, even when it's serialized as a JSON. Manipulating internals (inc. node private properties) can potentially lead to unexpected behavior/errors in future releases.

The initialEditorState can take many shapes:

export type InitialEditorStateType = null | string | EditorState | (() => void);

  • null -> empty EditorState (just a RootNode)
  • string -> a JSON stringified EditorState. Behind the scenes it calls JSON.parse(editor.setEditorState)
  • EditorState -> an EditorState. Behind the scenes it calls - editor.setEditorState() (the undo-redo/History plugin uses this) (() => void) -> an editor.update function

The one you're interested in is (() => void) -> an editor update.

You can run an editor.update like follows:

<LexicalPlainTextPlugin initialEditorState={() => {
  const paragraph = $createParagraphNode();
  const text = $createTextNode('foo');
  paragraph.append(text);
  $getRoot().append(paragraph);
  $getRoot().selectEnd();
}} />

No need to cache (useCallback) initialEditorState as it's only processed once

Side note: we're planning to move initialEditorState (that currently lives in LexicalPlainTextPlugin and LexicalRichTextPlugin) to LexicalComposer but it will work the same way.


We recommend avoiding manually handcrafted solutions too:

// PrepopulatePlugin.js
useLayoutEffect(() => {
  editor.update(() => {
    // Prepopulate
  });
}, [editor]);

We built LexicalContentEditable to work well with SSR and handle the contenteditable appropriately. If you were to build your own custom solution you would have to repeat this process.

like image 138
zurfyx Avatar answered Nov 18 '25 21:11

zurfyx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!