Skip to content

Instantly share code, notes, and snippets.

@ndpniraj
Created October 6, 2022 13:43
Show Gist options
  • Save ndpniraj/633474d23145499c5a3c39b017f43be4 to your computer and use it in GitHub Desktop.
Save ndpniraj/633474d23145499c5a3c39b017f43be4 to your computer and use it in GitHub Desktop.
Tooltip Component Using React & Tailwind CSS
import { FC } from "react";
import { BsTypeBold } from "react-icons/bs";
import ToolTip from "./ToolTip";
interface Props {}
const App: FC<Props> = (props): JSX.Element => {
return (
<div className="mx-auto max-w-3xl p-10">
<ToolTip tooltip="I am tooltip">
<button className="bg-gray-900 text-white p-3 rounded">
Show Me Tooltip
</button>
</ToolTip>
<div className="py-10">
<ToolTip tooltip="Bold">
<button className="bg-gray-900 text-white p-3 rounded">
<BsTypeBold />
</button>
</ToolTip>
</div>
</div>
);
};
export default App;
import { FC, ReactNode, useRef } from "react";
interface Props {
children: ReactNode;
tooltip?: string;
}
const ToolTip: FC<Props> = ({ children, tooltip }): JSX.Element => {
const tooltipRef = useRef<HTMLSpanElement>(null);
const container = useRef<HTMLDivElement>(null);
return (
<div
ref={container}
onMouseEnter={({ clientX }) => {
if (!tooltipRef.current || !container.current) return;
const { left } = container.current.getBoundingClientRect();
tooltipRef.current.style.left = clientX - left + "px";
}}
className="group relative inline-block"
>
{children}
{tooltip ? (
<span
ref={tooltipRef}
className="invisible group-hover:visible opacity-0 group-hover:opacity-100 transition bg-blue-500 text-white p-1 rounded absolute top-full mt-2 whitespace-nowrap"
>
{tooltip}
</span>
) : null}
</div>
);
};
export default ToolTip;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment