简体   繁体   中英

Creating a tooltip on hover in React

I made a tooltip which appears when I hover on an element, and shows the full name of the product, productName .

<div
  className="product-select-info"
  onMouseEnter={e => productNameHandleHover(e)}
  onMouseLeave={productNameHandleNoHover}
>
  {productName}
  <div
    className="tooltip"
    style={{
      display: isTooltipShown ? "block" : "none",
      top: mouseLocation.y,
      left: mouseLocation.x,
    }}
  >
    {productName}
  </div>
</div>

And here are my handlers:

const productNameHandleHover = (event: any): void => {
  setmouseLocation({
    x: event.pageX,
    y: event.pageY,
  });
  setisTooltipShown(true);
};

const productNameHandleNoHover = (): void => {
  setisTooltipShown(false);
};

My problem is, I want to only show the tooltip after like 0.5 seconds. Currently, the tooltip appears as soon as the mouse goes over the div. How do I achieve this? I tried using setTimeout but I was just running into issues with that.

It is good to use css transitions as ritaj has mentioned in the comments.

But if you absolutely want javascript implementation, Whenever you are hovering over your element, set a class variable to be true.

const productNameHandleHover = (event: any): void => {
  this.hovering = true;
  ...
}

and set it false whenever it is not.

const productNameHandleNoHover = (): void => {
  this.hovering = false;
  setisTooltipShown(false);
};

And when you actually set your tooltip check if your class variable is set or not.

const productNameHandleHover = (event: any): void => {
  this.hovering = true;
  setmouseLocation({
    x: event.pageX,
    y: event.pageY,
  });
  setTimeout(() => {
    if (this.hovering) {
      setisTooltipShown(true);
    }
  }, 500)
};

Here is a codesandbox that does what you need.

But you can already see the amount of effort you have to put in. So coming back to the original point. Using css transitions is a better option

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM