javascriptreactjshovertooltipreact-bootstrap

react-bootstrap prevent tooltip hide when mouse cursor is inside tooltip


I'm using react-bootstrap's <OverlayTrigger> and <Tooltip> to show a tooltip with a link in when the user hovers on a disabled button, like this:

    <OverlayTrigger
      placement="bottom"
      delay={{ hide: 500 }}
      overlay={<Tooltip>
          Click <a href="/billing">here</a>
      </Tooltip>}
    >
      <Button disabled>I am a button</Button>
    </OverlayTrigger>

But the user can never click the link, because the tooltip hides automatically when their cursor leaves the button. I can delay the hide for longer, but not prevent it hiding if the user's cursor is inside the tooltip - does anyone know how to achieve that?


Solution

  • I don't think React-Bootstrap's OverlayTrigger provide a built-in way to handle this scenario where tooltip stays visible when the user's cursor is inside the tooltip

    So you can use the Overlay component and manage the toolip's visibility state manually.

    Use below random copied code for integration.

    import React, { useState, useRef } from 'react';
    import { Button, Overlay, Tooltip } from 'react-bootstrap';
    
    const CustomTooltipButton = () => {
      const [show, setShow] = useState(false);
      const target = useRef(null);
    
      const handleMouseEnter = () => setShow(true);
      const handleMouseLeave = (e) => {
         if (!target.current.contains(e.relatedTarget)) {
          setShow(false);
        }
      };
    
      return (
        <>
          <Button
            ref={target}
            onMouseEnter={handleMouseEnter}
            onMouseLeave={handleMouseLeave}
            disabled
          >
            I am a button
          </Button>
    
          <Overlay target={target.current} show={show} placement="bottom">
            {(props) => (
              <Tooltip
                {...props}
                onMouseEnter={handleMouseEnter}
                onMouseLeave={handleMouseLeave}
              >
                Click <a href="/billing">here</a>
              </Tooltip>
            )}
          </Overlay>
        </>
      );
    };
    
    export default CustomTooltipButton;