DEV Community

Cover image for Custom 'Tooltip' component using Tailwind and React Js
Muhammad Azfar Aslam
Muhammad Azfar Aslam

Posted on • Updated on

Custom 'Tooltip' component using Tailwind and React Js

Bonjour
I hope you all guys are good in health. I always prefer creating custom components (like a tooltip) instead of libraries because libraries mostly bring extra code. Of course, for major functionality. You should use a library as its code is optimized and provide a variety of possibilities.

Let's come back to our original topic. The reason behind choosing Tailwind instead of bootstrap.

  1. It is Highly Customizable.
  2. It Has Common Utility Patterns.
  3. It Can Be Optimized Using Purge CSS.
  4. It Enables Building Complex Responsive Layouts Freely.
  5. It Facilitates Fluid Community Interaction.

I would not explain these points in detail but I hope they're enough to give an idea.

import React, { ReactNode, useState } from "react";

export const Tooltip = ({ message, children }: { message: string; children: ReactNode }) => {
  const [show, setShow] = useState(false);
  return (
    <div className="relative flex flex-col items-center group">
      <span className="flex justify-center" onMouseEnter={() => setShow(true)} onMouseLeave={() => setShow(false)}>
        {children}
      </span>
      <div className={`absolute whitespace-nowrap bottom-full flex flex-col items-center  group-hover:flex ${!show ? "hidden" : null}`}>
        <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>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Now, you can simply import this and call it like below

<Tooltip message="Hello, world!">
   <InfoIcon />
</Tooltip>
Enter fullscreen mode Exit fullscreen mode

You can style your tooltip box of any type. Also, it will allow you to style info text which you can not normally with an npm package. I hope it was helpful,
Please like and share this post.
You can also connect with me on LinkedIn 😉

Top comments (4)

Collapse
 
jeremy0x profile image
Jeremiah Aworetan

Thanks for this. Love the simplicity. Just what I needed.

Collapse
 
muhammadazfaraslam profile image
Muhammad Azfar Aslam

You're welcome Jeremiah, your kind words mean a lot to me. :)