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?
2
Answers
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:
then add a global event listener to execute whenever the escape key is pressed inside the
useEffect
hook:and set
isOpen
property in your tooltip component: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.
It’s important to note that globalEventOff and eventOff properties might not directly support the behavior you’re looking for with key presses. These properties are typically used to define events that cause the tooltip to not show or hide based on mouse actions (like click), not specifically keyboard events.