Detect click outside a react component using React Hooks

Many more developers are facing difficulties to detect the click event outside of the element in ReactJS therefore we’ll show you how to detect click outside a react component using React Hooks.

Why do we need it?

In the real project, we might need to handle an event when we click outside of a react component. Based on the outside event we can show or hide the element or manage some other components.

Detect click outside a react component

Use the following code to detect outside click events.

In the above code, we have added the event listener of the click event and remove it on component unmount.

Also we are handling the initial state of the component for visibility and reference of the component to detect outside click.

At last we are returning the reference, visibility state and method to change the visibility state and those attributes are useful to detect outside click.

Example

Let’s take a previous example, where we have implemented color picker in react. Now we will show a color picker on click of the input field and hide it when we detect a click outside a color picker.

First, we have to create a custom hooks to detect click event. Use the below code to create a custom hooks.

useVisible.js

Use the above hooks in the App.js file to manage show/hide color picker on click.

App.js

We are also showing the selected color in box along with the color code for live view.

Output

Run the project and check out the output in browser.

Output - Detect click outside a react component using React Hooks - Clue Mediator
Output – Detect click outside a react component using React Hooks – Clue Mediator

That’s it for today.
Thank you for reading. Happy Coding..!!

Demo & Source Code

Github Repository StackBlitz Project

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *