Getting access to the editor from outside the React component? #2223
Answered
by
neongreen
neongreen
asked this question in
Questions & Help
-
I have a React component wrapping the editor, and I want it to have methods that interact with the editor, e.g. let Tiptap = forwardRef((props: { content: string }, ref) => {
const editor = useEditor({
extensions = ...,
content: props.content,
})
const editorRef = useRef(editor)
useImperativeHandle(ref, () => ({
clearContent: () => {
editorRef.current?.commands.clearContent()
}
}))
return (
<EditorContent editor={editor} />
)
})
Tiptap.displayName = 'Tiptap'
export { Tiptap } However, What am I doing wrong? |
Beta Was this translation helpful? Give feedback.
Answered by
neongreen
Dec 2, 2021
Replies: 1 comment 1 reply
-
Apparently This is how I fixed it: export type TiptapMethods = {
clearContent: () => void
}
let Tiptap = forwardRef((props: { content: string }, ref: React.ForwardedRef<TiptapMethods>) => {
const editor = useEditor({
extensions,
content: props.content,
})
const editorRef: React.MutableRefObject<Editor | null> = useRef(null)
useImperativeHandle(ref, () => ({
clearContent: () => {
console.log('clearContent')
console.log(editorRef)
editorRef.current?.commands.clearContent()
}
}))
if (!editor) return null
editorRef.current = editor
return (
<EditorContent editor={editor} />
)
})
Tiptap.displayName = 'Tiptap'
export { Tiptap } |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
neongreen
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Apparently
useEditor
returns null at first and later it doesn't.This is how I fixed it: