Skip to content

Instantly share code, notes, and snippets.

@zbeyens
Last active February 18, 2024 10:48
Show Gist options
  • Save zbeyens/cf03f165b3620a6d7100a4ee0f076665 to your computer and use it in GitHub Desktop.
Save zbeyens/cf03f165b3620a6d7100a4ee0f076665 to your computer and use it in GitHub Desktop.
'use client';
export function withTooltip<
T extends React.ComponentType<any> | keyof HTMLElementTagNameMap,
>(Component: T) {
return React.forwardRef<
React.ElementRef<T>,
React.ComponentPropsWithoutRef<T> & {
tooltip?: React.ReactNode;
tooltipContentProps?: Omit<
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>,
'children'
>;
tooltipProps?: Omit<
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Root>,
'children'
>;
}
>(function ExtendComponent(
{ tooltip, tooltipContentProps, tooltipProps, ...props },
ref
) {
const isMounted = useMounted();
const component = <Component ref={ref} {...(props as any)} />;
if (tooltip && isMounted) {
return (
<Tooltip {...tooltipProps}>
<TooltipTrigger asChild>{component}</TooltipTrigger>
<TooltipContent {...tooltipContentProps}>{tooltip}</TooltipContent>
</Tooltip>
);
}
return component;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment