-
-
Notifications
You must be signed in to change notification settings - Fork 329
Expand file tree
/
Copy pathTooltip.tsx
More file actions
81 lines (73 loc) · 2.1 KB
/
Tooltip.tsx
File metadata and controls
81 lines (73 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import * as React from 'react'
import {
useFloating,
useHover,
useInteractions,
FloatingPortal,
offset,
shift,
flip,
autoUpdate,
} from '@floating-ui/react'
interface TooltipProps {
content: React.ReactNode
children: React.ReactElement
placement?: 'top' | 'right' | 'bottom' | 'left'
className?: string
}
export function Tooltip({
content,
children,
placement = 'top',
className = '',
}: TooltipProps) {
const [isOpen, setIsOpen] = React.useState(false)
const [isMounted, setIsMounted] = React.useState(false)
const portalRoot = React.useRef<HTMLElement | null>(null)
const { refs, floatingStyles, context } = useFloating({
open: isOpen,
onOpenChange: setIsOpen,
placement,
middleware: [offset(5), flip(), shift()],
whileElementsMounted: autoUpdate,
})
const hover = useHover(context)
const { getReferenceProps, getFloatingProps } = useInteractions([hover])
// Ensure DOM is ready before rendering the portal
React.useEffect(() => {
// Only set portalRoot if we're in a browser environment
if (typeof window !== 'undefined' && typeof document !== 'undefined') {
portalRoot.current = document.body
setIsMounted(true)
}
return () => {
// Clean up on unmount to prevent memory leaks
setIsMounted(false)
portalRoot.current = null
}
}, [])
return (
<>
{/* eslint-disable-next-line react-hooks/refs */}
{React.cloneElement(children, {
// eslint-disable-next-line react-hooks/refs
ref: refs.setReference,
...getReferenceProps(),
} as any)}
{isMounted && portalRoot.current && (
<FloatingPortal root={portalRoot.current}>
{isOpen && (
<div
ref={refs.setFloating /* eslint-disable-line react-hooks/refs */}
style={floatingStyles}
{...getFloatingProps()}
className={`z-50 rounded-md bg-gray-900 px-3 py-1.5 text-sm text-white shadow-lg dark:bg-gray-800 ${className}`}
>
{content}
</div>
)}
</FloatingPortal>
)}
</>
)
}