DEV Community

Cover image for How to Detect a Click Outside of a React Component using Hooks?
Ateev Duggal
Ateev Duggal

Posted on • Originally published at tekolio.com

How to Detect a Click Outside of a React Component using Hooks?

As web developers, we may come across situations where we might have to detect when a user clicks outside of a specific element, such as a modal or dropdown menu. This can be useful for closing the element or triggering some other action when the user clicks outside of it.

In React, you can detect a click outside of a component by using a technique called "event bubbling" or "event capturing". This involves attaching an event listener to the document object and checking if the click target is outside of the component.

In this blog post, we'll understand how to detect a click outside of a React component using the useRef and useEffect hooks in a step-by-step fashion using an example problem as it is better to understand things using practical examples.

Let’s start, but first to create a React app to understand this concept.

Index

  1. Creating the React App
  2. What are we making?
  3. Working on the App
  4. Detecting the Outside Click of a functional component
  5. Use a React Ref to Create a Clickable Area
  6. Creating an event listener for the clickable area
  7. Checking if the click is outside of the React component
  8. logic inside the if statement.
  9. Different Ways using which we can Detect a Click Outside of a React Component
  10. Conclusion
  11. Frequently Asked Question

What are we making?

In this app, we will be making a counter app that contains a button wrapped up by a div. The initial value of the counter is 0. With each button click, the value of the counter gets increased by 1, while will decrease if anything other than the button and the wrapper element div is clicked. See the gif below to understand

Detecting a click outside a component

Continue Reading...

Top comments (0)