Vasyl Putra

React Tailwind tooltip

Introducing my custom Tooltip component for React and Tailwind css! This component enhances your application's user experience by displaying helpful messages on hover, all without the need to download an additional library.

Benefits of using our shared Tooltip component:

  1. Consistency: Ensures a unified look and feel across your application.
  2. Lightweight: Reduces dependency bloat by keeping your bundle size smaller.
  3. Customizable: Easily tailor the Tooltip to fit your design requirements.
  4. Simplicity: Integrates seamlessly into your existing React components.

By using this shared component, you maintain control over your codebase while delivering a polished and interactive user interface.

Tooltip.tsx
1
import React, { ReactNode, useState } from "react";
2
3
/**
4
* Tooltip component that displays a message when hovered over.
5
*
6
* @param {Object} props - The component props.
7
* @param {string} props.message - The message to display in the tooltip.
8
* @param {ReactNode} props.children - The content to display as the trigger for the tooltip.
9
* @returns {JSX.Element} The Tooltip component.
10
*/
11
12
interface TooltipProps {
13
message: string;
14
children: ReactNode;
15
}
16
17
export const Tooltip = ({ message, children }: TooltipProps) => {
18
// State to track whether the tooltip is currently being displayed
19
const [show, setShow] = useState<boolean>(false);
20
21
// Function to handle the mouse enter event
22
const handleMouseEnter = () => {
23
setShow(true);
24
};
25
26
// Function to handle the mouse leave event
27
const handleMouseLeave = () => {
28
setShow(false);
29
};
30
31
// Check if the tooltip should be displayed
32
const shouldDisplayTooltip = show && !!message;
33
34
return (
35
// The tooltip container
36
<div className="group relative flex flex-col items-center">
37
{/* The trigger content */}
38
<span
39
className="flex justify-center"
40
// Show the tooltip when the mouse enters the trigger
41
onMouseEnter={handleMouseEnter}
42
// Hide the tooltip when the mouse leaves the trigger
43
onMouseLeave={handleMouseLeave}
44
>
45
{children}
46
</span>
47
{/* The tooltip itself */}
48
<div
49
className={`absolute bottom-full flex flex-col items-center whitespace-nowrap group-hover:flex ${
50
shouldDisplayTooltip ? "" : "hidden"
51
}`}
52
>
53
{/* The tooltip message */}
54
<span className="whitespace-no-wrap relative z-10 rounded-md bg-gray-600 p-2 text-xs leading-none text-white shadow-lg">
55
{message}
56
</span>
57
{/* The arrow pointing to the trigger */}
58
<div className="-mt-2 h-3 w-3 rotate-45 bg-gray-600" />
59
</div>
60
</div>
61
);
62
};
By a coffee for Puvvl

Keep Updated

Stay ahead of the curve with Puvvl.dev! Join our mailing list to receive exclusive, handpicked updates and important news. Be the first to know about our latest advancements and innovations.