Tooltip component


Let's see how to create a Tooltip component that can be re-used in your codebase when a tooltip is required.

Free
4 minutes read

Minimal tooltip example

💾 InteractionData: where the tooltip info is stored.

Our tooltip component is going to expect one property only: an object of type InteractionData.

This object stores everything we need to build a tooltip. At the very least we need some positions (xPos and yPos) and a title to display (name here)

type InteractionData = {
  xPos: number;
  yPos: number;
  name: string;
}

type TooltipProps = {
  interactionData: InteractionData | undefined;
};

But we could put many other things! A color for the border, some values to display, a link to an image.. Anything really.

🦴 Tooltip component skeleton

The Tooltip component uses some props of type TooltipProps, which is basically just an interactionData object.

If this object is undefined (user is not hovering anything), then we do not return anything;

// Tooltip.tsx
export const Tooltip = ({ interactionData }: TooltipProps) => {

  if (!interactionData) {
    return null;
  }

  ... Do something with interactionData otherwise
};

🍔 The meat

Now, we just need to return something based on the interactionData information.

Do not forget to use xPos and yPos to put the tooltip at the right position!

const { xPos, yPos, name } = interactionData;

return (
  <div
    style={{
      left: xPos,
      top: yPos,
    }}
  >
    <b>{name}</b>
  </div>
);


Exercises