I have an Overlay which is opened by clicking an icon button. In that Overlay, I’m using the useClickAway
hook exported by the react-use
library –
useClickAway(overlayRef, hideOverlay);
Basically, whenever a user clicks anywhere outside the overlay dom node, it hides this overlay.
But with this, I’m facing one issue when a user clicks on that icon button
(which opens this overlay), this overlay first closes and then re-opens, which causes the flickering of the overlay.
How can I make clicking on this icon button
an exception for this useClickAway
hook?
I have tried adding event.stopPropagation
to click event handler on icon button
but it didn’t work.
Codesandbox Link for same – https://codesandbox.io/s/useclickaway-hook-krd6y6
3
Answers
Have fixed it by adding following event listener to button -
It sounds like you want to prevent the overlay from immediately closing and reopening when the icon button is clicked, while still allowing it to close when clicking outside the overlay. Since the
useClickAway
hook triggers thehideOverlay
function when clicking outside the overlay, you’ll need a mechanism to temporarily disable this behavior when the icon button is clicked.One way to achieve this is by using a flag to determine whether the overlay should be closed or not based on the last click event target. Here’s an example of how you could modify your code to achieve this:
In this example, the
shouldClose
flag is used to determine whether the overlay should be closed when theuseClickAway
hook triggers thehideOverlay
function. When the icon button is clicked, theshouldClose
flag is temporarily set tofalse
, preventing the overlay from closing immediately. Thee.stopPropagation()
call prevents the event from propagating and affecting the overlay’s closing behavior.Remember that the above example assumes a basic overlay structure. You might need to adapt it to fit your specific code and styling.
The
onClickAway
hook doesn’t support excluding HTML elements, its callback will be called if the element you click is not the descendant element of the overlay element. See!el.contains(event.target)
.You have to exclude the HTML elements by yourself. You can get the
mousedown
event
object in the handler. SeeonClickAway: (event: E) => void
If the
event.target
is the button element, don’t close the overlay.codesandbox