I know there is an AutoFocusPlugin in @lexical/react
, but I can't seem to get it to work properly on initial render.
Take the following code (which seems to be matching the current implementation of AutoFocusPlugin.js
) - sandbox here :
import React, { FC, useLayoutEffect } from "react";
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
import LexicalComposer from "@lexical/react/LexicalComposer";
import LexicalPlainTextPlugin from "@lexical/react/LexicalPlainTextPlugin";
import LexicalContentEditable from "@lexical/react/LexicalContentEditable";
const AutofocusPlugin = () => {
const [editor] = useLexicalComposerContext();
useLayoutEffect(() => {
editor.focus();
}, [editor]);
return null;
};
export const MyEditor = () => {
return (
<LexicalComposer initialConfig={{ onError: () => null }}>
<LexicalPlainTextPlugin
contentEditable={<LexicalContentEditable />}
placeholder={null}
/>
<AutofocusPlugin />
</LexicalComposer>
);
};
I would expect the editor to initialize focused, but it does not.
Deferring the focus call to the async stack seems to solve this inside the sandbox:
useLayoutEffect(() => {
setTimeout(() => editor.focus(), 0);
}, [editor]);
but does not reliably work in Cypress/Storybook for me.
So what am I doing wrong?