Languages
[Edit]
EN

React - detect click outside component hook (works with nested elements)

10 points
Created by:
trincot
360

In this short article, we would like to show how in React write a custom hook that handles clicks outside component.

Hook to detect click outside of the component in React.
Hook to detect click outside of the component in React.

Note: presented in this article solution is able to handle outside clicks even clicked component contains nested elements.

Quick solution:

 

Practical example

Edit

To avoid unnecessary function recreation useOutideClickHandler() body was moved to addOutideClickListener() function.

1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - detect click outside component hook (works with nested elements)
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join