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:
- Consistency: Ensures a unified look and feel across your application.
- Lightweight: Reduces dependency bloat by keeping your bundle size smaller.
- Customizable: Easily tailor the Tooltip to fit your design requirements.
- 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.tsx1import React, { ReactNode, useState } from "react";23/**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*/1112interface TooltipProps {13message: string;14children: ReactNode;15}1617export const Tooltip = ({ message, children }: TooltipProps) => {18// State to track whether the tooltip is currently being displayed19const [show, setShow] = useState<boolean>(false);2021// Function to handle the mouse enter event22const handleMouseEnter = () => {23setShow(true);24};2526// Function to handle the mouse leave event27const handleMouseLeave = () => {28setShow(false);29};3031// Check if the tooltip should be displayed32const shouldDisplayTooltip = show && !!message;3334return (35// The tooltip container36<div className="group relative flex flex-col items-center">37{/* The trigger content */}38<span39className="flex justify-center"40// Show the tooltip when the mouse enters the trigger41onMouseEnter={handleMouseEnter}42// Hide the tooltip when the mouse leaves the trigger43onMouseLeave={handleMouseLeave}44>45{children}46</span>47{/* The tooltip itself */}48<div49className={`absolute bottom-full flex flex-col items-center whitespace-nowrap group-hover:flex ${50shouldDisplayTooltip ? "" : "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};