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

Ateev Duggal
2 min readMay 26, 2023

--

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

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

Detect an outside click

Continue Reading…

--

--

Ateev Duggal

I am a front-end developer from India with over one year of experience in freelancing with skills like Git, HTML5, CSS3, Bootstrap 4&5, and React.