Files
tiptap/packages/react/src/FloatingMenu.tsx
Tomas Valenta 561941d5e0 fix: Remove element.current from useEffect in BubbleMenu and FloatingMenu (#2297)
* Remove `element.current` from `useEffect` dependencies

Changes to the `element.current` don't trigger `useEffect` rerender and shouldn't be used in the dependency array.
One discussion about is this is for example here: https://stackoverflow.com/questions/60476155/is-it-safe-to-use-ref-current-as-useeffects-dependency-when-ref-points-to-a-dom

It's also causing some subtle bugs when mounting and unmounting editors.

* Fix `FloatingMenu` and `BubbleMenu` element references

* Fix linting errors

* Don't register plugin when the editor is already destroyed; Simplify `HTMLElement` reference handling

* Fix lint error
2021-12-22 12:13:36 +01:00

52 lines
1.1 KiB
TypeScript

import React, {
useEffect, useState,
} from 'react'
import { FloatingMenuPlugin, FloatingMenuPluginProps } from '@tiptap/extension-floating-menu'
type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>
export type FloatingMenuProps = Omit<Optional<FloatingMenuPluginProps, 'pluginKey'>, 'element'> & {
className?: string,
}
export const FloatingMenu: React.FC<FloatingMenuProps> = props => {
const [element, setElement] = useState<HTMLDivElement | null>(null)
useEffect(() => {
if (!element) {
return
}
if (props.editor.isDestroyed) {
return
}
const {
pluginKey = 'floatingMenu',
editor,
tippyOptions = {},
shouldShow = null,
} = props
const plugin = FloatingMenuPlugin({
pluginKey,
editor,
element,
tippyOptions,
shouldShow,
})
editor.registerPlugin(plugin)
return () => editor.unregisterPlugin(pluginKey)
}, [
props.editor,
element,
])
return (
<div ref={setElement} className={props.className} style={{ visibility: 'hidden' }}>
{props.children}
</div>
)
}