stargaze-studio/components/Tooltip.tsx

46 lines
1.3 KiB
TypeScript
Raw Normal View History

2022-07-13 13:56:36 +00:00
import clsx from 'clsx'
import type { ComponentProps, ReactElement, ReactNode } from 'react'
import { cloneElement, useState } from 'react'
import { usePopper } from 'react-popper'
export interface TooltipProps extends ComponentProps<'div'> {
label: ReactNode
children: ReactElement
2023-03-07 07:33:59 +00:00
placement?: 'top' | 'bottom' | 'left' | 'right'
2022-07-13 13:56:36 +00:00
}
export const Tooltip = ({ label, children, ...props }: TooltipProps) => {
const [referenceElement, setReferenceElement] = useState(null)
const [popperElement, setPopperElement] = useState<any>(null)
const [show, setShow] = useState(false)
const { styles, attributes } = usePopper(referenceElement, popperElement, {
2023-03-07 07:33:59 +00:00
placement: props.placement ? props.placement : 'top',
2022-07-13 13:56:36 +00:00
})
return (
<>
{/* children with attached ref and mouse events */}
{cloneElement(children, {
...children.props,
ref: setReferenceElement,
onMouseOver: () => setShow(true),
onMouseOut: () => setShow(false),
})}
{/* popper element */}
{show && (
<div
{...props}
{...attributes.popper}
2023-03-07 09:12:43 +00:00
className={clsx('py-1 px-2 m-1 text-sm bg-slate-900 rounded shadow-md', props.className)}
2022-07-13 13:56:36 +00:00
ref={setPopperElement}
style={{ ...styles.popper, ...props.style }}
>
{label}
</div>
)}
</>
)
}