javascriptreactjsreact-tooltip

Close React Tooltip at Escape character


Requirement: I am using @react-tooltip 4.2, I need to close it when the user presses escape.

Unsuccessful Attempt:

<ReactTooltip id={ "tooltip" } effect="solid" role="status" globalEventOff={ ['click', 'escape'] } eventOff="escape">
     Some Content
</ReactTooltip>

What am I doing wrong?


Solution

  • One solution is to create a boolean state to hide the tooltip whenever the escape key is pressed and similarly you also need to show it manually. First create a state variable:

    const [isOpen, setIsOpen] = useState(false)
    

    then add a global event listener to execute whenever the escape key is pressed inside the useEffect hook:

    useEffect(() => {
      const handleKeyPress = (event) => {
        if (event.key === 'Escape') {
          setIsOpen(false);
        }
      };
    
      document.addEventListener('keydown', handleKeyPress);
    
      return () => {
        document.removeEventListener('keydown', handleKeyPress); // remove the event listener when this component is no longer used
      };
    }, []);
    

    and set isOpen property in your tooltip component:

    <ReactTooltip id={ "tooltip" } effect="solid" role="status" isOpen={isOpen}>
         Some Content
    </ReactTooltip>
    

    then finally don't forget to show the tooltip by setting onMouseEnter={() => setIsOpen(true)} in your desired component.

    You can also use ref property to hide the tooltip, without managing the state manually, see Imperative mode (ref).

    You can look into the @react-tooltip docs example. hope it helps.