Why can't my custom Lexical React plugin use the LexicalComposerContext?

2.8k Views Asked by At

function UpdateStatePlugin(props) {
  ...
  const [editor] = useLexicalComposerContext();
  ...
}

function Notes() {
  ...

  const initialConfig = {
    ...
  };

  return (
    <LexicalComposer initialConfig={initialConfig}>
      ...
      <UpdateStatePlugin />
    </LexicalComposer>
  )
}

This fails with 'useLexicalComposerContext' is not defined

I followed this guide and found 1 mention of someone running into a similar problem here. In both cases the structure seems to resemble what I have written. Would appreciate any help!

2

There are 2 best solutions below

1
On BEST ANSWER

It's ok to define UpdateStatePlugin in the same file. The important part is that UpdateStatePlugin needs to be a child of LexicalComposer.

Your error, 'useLexicalComposerContext' is not defined, looks like one you'd see if you were missing an import. Try adding this to the top of your file:

import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
1
On

You shouldn't be defining UpdateStatePlugin within the render body of Notes, you should define it outside as its own component.

function UpdateStatePlugin(props) {
    const [editor] = useLexicalComposerContext();
    // ...
}

function Notes() {
    // return (...)
}

If you are doing this because you are creating UpdateStatePlugin to use some outside variable, then you instead should be passing that in as a prop.

function Notes() {
    const [someState] = useState();
    
    function UpdateStatePlugin() {
        useLexicalComposerContext();

        // Let's say you are using `someState` here, this isn't "thinking in React"
        doStuff(someState);
    }

    // ...
}

Instead you make the component accept someState as a prop, and then pass it in during render

function UpdateStatePlugin(props) {
    useLexicalComposerContext();

    // Takes in `{ someState }` as a prop!
    doStuff(props.someState);
}

function Notes() {
    const [someState] = useState();

    // ...

    return <UpdateStatePlugin someState={someState} />;
}