How to Create a Tooltip using TailwindCSS in JavaScript

How can we create a simple tooltip using TailwindCSS and JavaScript?

Suppose we’re working in React.js or Next.js.

We want to create a generic, reusable tooltip component for our project.

Let’s also use TypeScript!

1. Create a Tooltip component

Let’s create a Tooltip.tsx component.

Props. We’ll want to pass in a message string that will be displayed in the tooltip upon hover. We’ll also take in the children props, which will be the element we hover over to trigger the tooltip.

import { ReactNode } from "react";
export const Tooltip = ({ 
  message, children 
} : {
  message: string, children: ReactNode 
}) => {
  return (
    <div className="relative flex flex-col items-center group">
      <div className="absolute bottom-0 flex flex-col items-center hidden mb-6 group-hover:flex">
        <span className="relative z-10 p-2 text-xs leading-none text-white whitespace-no-wrap bg-gray-600 shadow-lg rounded-md">{message}</span>
        <div className="w-3 h-3 -mt-2 rotate-45 bg-gray-600"></div>

The property that makes this work is the group utility class in Tailwind.

We can use this class to style elements based on the state of the parent element.

By marking the parent with the group class, we can use group-hover (or group-focus, group-active, etc.) on the appropriate child element.

I would encourage you to read up on these group-* modifiers in TailwindCSS.

2. Use Tooltip component

Once we’ve created our component, we can use this tooltip in our pages.

<Tooltip tooltipMessage="Resend Email">
  Hover over me!

We can easily pass in text, buttons, or random <div> elements into our new tooltip.