Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to make the MUI tooltip disappear while scrolling downwards is to listen for a scroll event on the window and then manually hide the tooltip using the Tooltip API.

Here is an example code snippet:

import React, { useState, useRef, useEffect } from 'react';
import { Tooltip } from '@mui/material';

const ExampleComponent = () => {
  const [showTooltip, setShowTooltip] = useState(false);
  const tooltipRef = useRef(null);

  useEffect(() => {
    const handleScroll = () => {
      setShowTooltip(false);
    };

    window.addEventListener('scroll', handleScroll);

    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);

  const handleTooltipOpen = () => {
    setShowTooltip(true);
  };

  const handleTooltipClose = () => {
    setShowTooltip(false);
  };

  return (
    <Tooltip
      ref={tooltipRef}
      open={showTooltip}
      onOpen={handleTooltipOpen}
      onClose={handleTooltipClose}
      title="Tooltip text"
    >
      <button>Hover me</button>
    </Tooltip>
  );
};

In this example, we listen for a scroll event on the window and then call setShowTooltip(false) to manually hide the tooltip. We also pass in a ref to the Tooltip component so we can access its API and call methods like open() and close().

Whenever the user hovers over the button, the handleTooltipOpen function is called to show the tooltip. If the user scrolls downwards, the handleScroll function is called to hide the tooltip.

Note that if you want the tooltip to reappear after the user stops scrolling, you can add a delay before calling setShowTooltip(false) or use a debounce technique to prevent excessive updates.