From a67b5f8a25dce81da40cf01c37f9ca5441749a02 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sat, 23 Sep 2023 15:10:05 -0500 Subject: [PATCH] lexical: add RefPlugin to set the ref --- src/features/compose/editor/index.tsx | 7 +++---- .../compose/editor/plugins/ref-plugin.tsx | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 4 deletions(-) create mode 100644 src/features/compose/editor/plugins/ref-plugin.tsx diff --git a/src/features/compose/editor/index.tsx b/src/features/compose/editor/index.tsx index b3173a12a..32bea7c7f 100644 --- a/src/features/compose/editor/index.tsx +++ b/src/features/compose/editor/index.tsx @@ -24,6 +24,7 @@ import { useNodes } from './nodes'; import AutosuggestPlugin from './plugins/autosuggest-plugin'; import FocusPlugin from './plugins/focus-plugin'; import MentionPlugin from './plugins/mention-plugin'; +import RefPlugin from './plugins/ref-plugin'; import StatePlugin from './plugins/state-plugin'; const LINK_MATCHERS = [ @@ -80,7 +81,7 @@ const ComposeEditor = React.forwardRef(({ onFocus, onPaste, placeholder, -}, editorStateRef) => { +}, ref) => { const dispatch = useAppDispatch(); const nodes = useNodes(); @@ -157,9 +158,6 @@ const ComposeEditor = React.forwardRef(({ /> { onChange?.(editor.getEditorState().read(() => $getRoot().getTextContent())); - if (editorStateRef && typeof editorStateRef !== 'function') { - editorStateRef.current = editor; - } }} /> @@ -170,6 +168,7 @@ const ComposeEditor = React.forwardRef(({ + ); diff --git a/src/features/compose/editor/plugins/ref-plugin.tsx b/src/features/compose/editor/plugins/ref-plugin.tsx new file mode 100644 index 000000000..b13cea3e1 --- /dev/null +++ b/src/features/compose/editor/plugins/ref-plugin.tsx @@ -0,0 +1,18 @@ +import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'; +import { LexicalEditor } from 'lexical'; +import React, { useEffect } from 'react'; + +/** Set the ref to the current Lexical editor instance. */ +const RefPlugin = React.forwardRef((_props, ref) => { + const [editor] = useLexicalComposerContext(); + + useEffect(() => { + if (ref && typeof ref !== 'function') { + ref.current = editor; + } + }, [editor]); + + return null; +}); + +export default RefPlugin;