How to add text programmatically with Lexical editor?
Asked Answered
S

2

6

I'm using draftjs so far and I like it but since draftjs is going to be retired I'm playing with lexical text editor. But I could not figure out even very basic thing, insert text programmatically.

How can I insert text programmatically? like draftjs's Modifier.insertText?

Thanks for advance. example codes or link to examples are very helpful.

Samples answered 11/8, 2022 at 6:52 Comment(0)
V
2

editor.update does the trick: https://lexical.dev/docs/concepts/editor-state#updating-state

Here is a working example with React: https://codesandbox.io/s/lexical-update-d035dn?file=/src/Editor.js

Viridescent answered 7/9, 2022 at 17:14 Comment(1)
Thanks! btw, how can I append text on existing paragraph? do we have an example for that?Samples
S
6

Create a component that can benefit from the Lexical instance context.

import { $getSelection } from 'lexical'; 
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';

const InsertText = () => {
      const [editor] = useLexicalComposerContext();
    
      useEffect(() => {
        editor.update(() => {
          const selection = $getSelection();
          if (selection) {
            selection.insertText('the text I wanted to insert');
          }
        });
      }, [editor]);
    
      return null;
    };

You can then add the component as child to the parent LexicalComposer provider.

Sialkot answered 4/10, 2022 at 21:8 Comment(0)
V
2

editor.update does the trick: https://lexical.dev/docs/concepts/editor-state#updating-state

Here is a working example with React: https://codesandbox.io/s/lexical-update-d035dn?file=/src/Editor.js

Viridescent answered 7/9, 2022 at 17:14 Comment(1)
Thanks! btw, how can I append text on existing paragraph? do we have an example for that?Samples

© 2022 - 2024 — McMap. All rights reserved.