How to create tooltip with React and TailwindCSS?

What is tooltip?

A tooltip is a small piece of text that appears when you hover your mouse over an element on a website or application. It is used to give you more information about that element. For example, if you hover over a button on a website, a tooltip may appear with a brief description of what the button does.

Tooltips can be helpful because they provide information without taking up a lot of space on the page. They are often used to give additional context or explain something that might not be immediately clear.

How to create Tooltip in React?

If you are browsing the internet, you might find the npm package for this called react-tooltip, which is okay to use, but a tooltip is just a small UI and we should be able to create it without any library.

Creating a tooltip is just a CSS thing, so if you are using TailwindCSS, we can easily create the tooltip with the available utility class from Tailwind and we can even add animation to make it more interesting. Here is an example of the tooltip we are going to build.

✨ You hover me!

To accomplish this look, we need to use the group-hover utility, and to show and hide the tooltip, we can use scale-0 and scale-100.

<div class="group relative m-12 flex justify-center">
  <button class="rounded bg-amber-500 px-4 py-2 text-sm text-white shadow-sm">Hover me!</button>
  <span class="absolute top-10 scale-0 rounded bg-gray-800 p-2 text-xs text-white group-hover:scale-100">✨ You hover me!</span>
</div>

And if you want to have animation like this, just add transition-all.

✨ You hover me!
<div class="group relative m-12 flex justify-center">
  <button class="rounded bg-amber-500 px-4 py-2 text-sm text-white shadow-sm">Hover me!</button>
  <span class="absolute top-10 scale-0 transition-all rounded bg-gray-800 p-2 text-xs text-white group-hover:scale-100">✨ You hover me!</span>
</div>

Bonus: Get the source code in TailwindCSS playground.

Wrap to React Component

So to make it reusable we can wrap to our react components like this.

export default function Tooltip({ message, children }) {
    return (
    <div class="group relative flex">
        {children}
        <span class="absolute top-10 scale-0 transition-all rounded bg-gray-800 p-2 text-xs text-white group-hover:scale-100">{message}</span>
    </div>
    )
}

And now you can use the component like this.

<Tooltip message={"✨ Coming soon!"}>
    <button>Subscribe</button>
</Tooltip>

Conclusion

So, it is possible to create a tooltip in React using TailwindCSS utility classes. By using the group-hover utility, you can show and hide the tooltip by using scale-0 and scale-100.

You can also add animation to the tooltip by using the transition-all utility. By wrapping the tooltip in a React component, you can easily reuse it throughout your application.

That's it for today let me know if you have any question, you can DM me on twitter.