How to detect a click outside of a React component - LogRocket Blog (2023)

Web developers tend to use different components to make their React-based web applications more dynamic for better usability and flexibility.

A React component is a stand-alone, reusable, and isolated UI building block written in JSX (or TSX). Web applications generally allow the user to interact with one component at a time; for example, a user can open an HTML popup window and interact with the content of the popup window. If the user clicks outside of the popup area, the web application closes the popup or prevents the user from closing the popup.

Web developers also use custom dropdown menus to allow users to choose from a list of multiple options. If the user clicks outside of the custom dropdown while it is open, the dropdown will close.

In such a scenario, when the user clicks outside of a certain component, we need to trigger some actions.

In this tutorial, I'll explain how you can extend your class-based functional React components to detect an external click, and I'll explain an alternative way to accomplish the same task using a popular npm library.

Detection of an external click of a functional component

Let's create an HTML tooltip by creating a functional React component calledinformation box🇧🇷 The tooltip is displayed when the user clicks a button and closes when the user clicks outside of the tooltip component. We need to detect a click outside of a React component to implement a solution for this scenario.

First, let's create a new React app to get started. Alternatively, you can add the following external click detection code to your existing React app.

Enter the following command and create a new application.

npx Create-React-App React-Outside-Click cd React-Outside-ClickYarn Start

Now we need to create a new functional component to implement the tooltip component. Paste the code below./src/components/InfoBoxFunctional.js.

importar { useEffect, useRef } de 'reaccionar'; Exportfunktion InfoBox(props) { const ref = useRef(null); const { onClickOutside } = adereços; useEffect(() => { const handleClickOutside = (evento) => { if (ref.current && !ref.current.contains( { onClickOutside && onClickOutside(); } }; document.addEventListener('click ', handleClickOutside, true); return () => { document.removeEventListener('click', handleClickOutside, true); }; }, [ onClickOutside ]); if(! devuelve nulo; return ( <div ref={ref} className='info-box'> {props.message} </div>);}

The above code snippet assigns the DOM reference to the current component instanceRefereevariable usinguseRefHook. After that, register a click handler in theuse effecthook for alldocumentto detect global click events.

We can also return a function with code to cleanuse effectHook, which means we can unregister our global click event listener when the component is unhooked. As you can see, the above code implements the cleanup code using theEliminar EventListenerDOM API function.

More than 200,000 developers use LogRocket to create better digital experiences. More information →

preparation ofinformation boxTooltip Components

oinformation boxThe component supports three accessories:

  • message: specifies the tooltip message
  • when clicked outside: defines a callback that we should fire when an external click event occurs
  • Show: Refers to the visibility state and indicates whether the component is hidden or visible. If true, the tooltip is visible; otherwise, the component function returnsNulland will not show any content

ohandleClickOutThe function is triggered every time the user clicks on the document. so if we callwhen clicked outsideImmediately,Tooltip disappearseven if the user clicks on the tooltip itself.

The above code checks if the user clicks the tooltip (or its children) via thecontainsDOM API function. Therefore, thewhen clicked outsideThe callback is executed when a click event occurs outside of the tooltip component instance.

oinformation boxthe component is now complete. Add the following CSS code to the./src/index.cssFile to apply some styles to theinformation boxComponent. You can also move your InfoBox-related CSS to a separate file if you want. we will use thoseindex.cssFile for demo purposes.

body { border: 0; Font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans serif; -Webkit font smoothing: antialiasing; -moz-osx-font-smoothing: grayscale;}.container { display: flex; justify-content: center; padding-top: 40vh;}.container .info-box-wrapper { position: relative;}.container .info-box { user selection: none; Width: 300px; Background: #ffc00d; Font size: 14px; Padding: 12px; box shadow: 2px 2px 12px rgba(0, 0, 0, 0,2); border radius: 4px; top: 20px; location: absolute;}

Lastly, update yours../src/App.jsFile with the following code for our main application to work.

import { useState } from 'react'; import {InfoBox} from './components/InfoBoxFunctional.js'; function App() { let [showInfo1, setShowInfo1] = useState(false); return ( <div className="container"> <div className="info-box-wrapper"> <button onClick={() => {setShowInfo1(true)}} style={{marginRight: '4px'}}> Wichtigste Funktion von InfoBox</button> <InfoBox show={showInfo1} onClickOutside={() => {setShowInfo1(false)}} message="Click outside to close"/> </div> </div> ); } export application pattern;

The above code shows a button with a click action that opens the infobox. EITHERinformation boxThe component is reusable (you can create many infoboxes) and, as always, we pass it the necessary accessories.

See how the app runs below. We can close the InfoBox instance by clicking outside of it. Also, it doesn't disappear when you click a button or component.

How to detect a click outside of a React component - LogRocket Blog (3)

Detecting an external click of a class-based component

The class-based component approach is very similar to the functional component approach. We use the same props, DOM APIs, and implementation logic, but we have to write our code in a class-based style. Add the following code./src/components/InfoBoxClassBased.js.

importar React desde 'react'; Exportar Klasse InfoBox erweitert React.Component { constructor(props) { super(props); this.ref = React.createRef(); this.handleClickOutside = this.handleClickOutside.bind(this); } handleClickOutside(evento) { if (this.ref.current && !this.ref.current.contains( { this.props.onClickOutside && this.props.onClickOutside(); } }; componentDidMount() { document.addEventListener('click', this.handleClickOutside, true); } componentWillUnmount() { document.removeEventListener('click', this.handleClickOutside, true); }; render () { if (! null zurückgeben; return ( <div ref={this.ref} className='info-box'> {this.props.message} </div>); }}

The code snippet above is similar to the function component code, but there are a few differences. We use for exampleReact.CreateRefinstead ofuseRefhook because weReact Hooks cannot be used with class-based components.

update yours nowApplication.jsAdd your new component references as shown below. Note that in the demo app we use both functional and class-based components, but feel free to just use the class-based implementation if you like.

Other great LogRocket articles:

  • Don't waste a moment withor reproduce, a newsletter curated by LogRocket
  • Learnhow LogRocket's Galileo reduces noise to proactively solve problems in your application
  • Use useEffect to reactto optimize the performance of your application
  • switch betweendifferent versions of Node
  • Find out how to animateYour React app with AnimXYZ
  • Explore Taurus, a new framework for building binaries
  • CompareNestJS x Express.js

Let's take a look at how the application runs again. There are now two instances of the InfoBox: the class-based implementation and the functional implementation.

How to detect a click outside of a React component - LogRocket Blog (4)

Here we use theCliqueevent to bind click event listeners. You can also use themouse downevent according to your wishes. you can find themFull source code on my GitHub.

Respond outside the click handler - an alternative method

As I mentioned earlier, you can easily add this external click detection code to any of your React components. The implementation consists of some DOM API function calls and React API uses. But nowadays we have npm libraries for literally everything we can think of related to React, including several libraries for this scenario. If you need to add this external click detection logic to many components and don't want to implement it yourself, you can use a library. EITHERReact outside click handleris a very popular library for handling external click events. As with any other npm library, this also affects the production package size a bit. The React Outside Click Handler increases the size of the production package by around 20KB. Let's update our project with this npm library. Let's modify the functional and class-based components by adding references to this npm library. Copy your current project to another directory and rename it toreact-off-click-lib🇧🇷 Install the npm library with the following command.

Add react thread outside click handler

Update both components. First add the following code./src/components/InfoBoxFunctional.js.

export function InfoBox(props) { if(! return null; return ( <div className='info-box'> {props.message} </div>);}

After that you can add the following code./src/components/InfoBoxClassBased.js.

Reaccionar de 'reaccionar' importieren; Klasse InfoBox exportieren React.Component { render() { if(! return null; return ( <div className='info-box'> {this.props.message} </div>); }}

As you can see now, we don't have our own third-party click detection implementation in any of the components. Let's use the npm library to re-enable the external click detection feature.

update yoursApplication.jswith the following code.

Import { useState } from 'react'; import {InfoBox as InfoBox1} from './components/InfoBoxFunctional.js'; import {InfoBox as InfoBox2} from './components/InfoBoxClassBased.js'; import OutsideClickHandler from 'react-outside -click-handler';Función App() { let [showInfo1, setShowInfo1] = useState(false); let [showInfo2, setShowInfo2] = useState(false);return ( <div className="container"> <div className="info-box-wrapper"> <button onClick={() => {setShowInfo1(true)}} style={{marginRight: '4px'}}>Show functional information table</button> <OutsideClickHandler onOutsideClick={() => {setShowInfo1(false)}}> <InfoBox1 show={showInfo1} message="To close outside click here"/> </OutsideClickHandler> </div> <div className="info-box-wrapper"> <button onClick={() => {setShowInfo2(true)}}>Show information table based on class</button > <OutsideClickHandler onOutsideClick={() => {setShowInfo2(false)}}> <InfoBox2 show={showInfo2} message="Click to close"/> </OutsideClickHandler> </div> </ div> ); } export predetermined application;

Here we package our InfoBox components with theexternal click handlercomponent defined in the library. we can use thoseonOutsideClickprop to pass a callback to execute some code when the user clicks outside of the specific component.

Take a look at the running app below. You'll see the same app as before, but this time we're using a third-party library.

How to detect a click outside of a React component - LogRocket Blog (5)

you can find themFull source code on my GitHub.


External click detection is useful in various UI elements such as popups, dropdowns, and menus. Web developers often tend to embed libraries even for simple things that they can implement themselves. Adding too many dependencies can slow down your web application, make the package size unmanageable, and make your code base less maintainable.

So it's best if you can implement this external click detection yourself, but if you can't, after all we need fast feature implementations for web apps, it's no problem if you integrate them.Library React external click controlleras it only slightly increases the size of the production package by just 20 kilobytes.

log rocket: Complete visibility of your production React apps

Debugging React apps can be difficult, especially when users encounter issues that are difficult to reproduce. If you are interested in monitoring and tracking Redux status, automatically detecting JavaScript errors, and tracking slow network requests and component load times,Store Log Rocket.

log rocketcombines session replay, product analytics, and bug tracking, enabling software teams to create the ideal web and mobile product experience. What does that mean for you?

Instead of guessing why errors occur or asking users for screenshots and log snippets, LogRocket lets you replay issues as if they happened in your own browser to quickly understand what went wrong.

No more loud warnings. Intelligent bug tracking lets you sort, categorize, and learn from issues. Receive notifications about serious user issues, not false positives. Less warnings, much more useful signal.

The LogRocket Redux middleware package adds an extra layer of transparency to your user sessions. LogRocket records all the actions and states of your Redux storages.

Modernize the way you debug your React apps -Start tracking for free.


How do you detect a click outside of a React component? ›

Detecting an outside click of a functional component

Let's build an HTML tooltip by creating a React functional component named InfoBox . The tooltip will appear when the user clicks a button, and it will be closed if the user clicks outside of the tooltip component.

How do you detect an outside click with React and hooks? ›

This hook allows you to detect clicks outside of a specified element. In the example below we use it to close a modal when any element outside of the modal is clicked.

How do you capture a click event in React? ›

React onClickCapture is an event handler that gets triggered whenever we click on an element. like onclick, but the difference is that onClickCapture acts in the capture phase whereas onClick acts in the bubbling phase i.e. phases of an event.

Which component can detect click as event? ›

jQuery closest() is used to see if the target from a click event has the dom element as one of its parents. If there is a match the click event belongs to one of the children and is thus not considered to be outside of the component.

How do you find click outside input? ›

So, for detecting a click outside an element, it would be best if you add a listener to the whole document element. Consequently, the main loop will go up the DOM from the clicked target element to search if the ancestor of that element belongs to the flyout container.

How do I detect a click outside an element in Javascript? ›

You can listen for a click event on document and then make sure #menucontainer is not an ancestor or the target of the clicked element by using . closest() . If it is not, then the clicked element is outside of the #menucontainer and you can safely hide it.

How do you listen to a click outside of a div? ›

We can use jQuery to listen to the click event on the html element to trigger an event when we click outside the element. We can then check which element is clicked in the event handler. The click event listener is then used to call click on it. $('html') is used to select an html element.

Can hooks be used outside of React components? ›

You can not use hooks outside a component function, it is simply how they work. But, you can make a composition of hooks. React relies on an amount and order of how hooks appear in the component function.

How do you detect touch in React? ›

touch detection in React
  1. Step 1: add touch events to container. On the parent container, add event handlers to onTouchStart and onTouchEnd. ...
  2. Step 2: capture the touchStart, detect where the press was. ...
  3. Step 3: capture the touch end, find the location, and get the difference so you can detect the direction.
Oct 27, 2019

How do you programmatically trigger a click event in React? ›

You could use the ref prop to acquire a reference to the underlying HTMLInputElement object through a callback, store the reference as a class property, then use that reference to later trigger a click from your event handlers using the HTMLElement.

How do you trigger a click event on an element? ›

The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.

How do you trigger keypress event in React? ›

If you're trying to create a keyboard event, you can make use of KeyboradEvent constructor. An enter key event can be dispatched like: const event = new KeyboardEvent('keypress', { key: 'enter', }); console. log(event) // KeyboardEvent {isTrusted: false, key: "enter", code: "", location: 0, ctrlKey: false, …}

How do you check if the element is clicked? ›

To check if an element is clicked, associate the click event listener with the element after getting the element's reference using the getElementById() method.

How do you know which element is clicked? ›

To get the clicked element, use target property on the event object. Use the id property on the event. target object to get an ID of the clicked element.

What is the event handler to detect a mouse click on a link? ›

The basic event handler for this is onClick. This event handler is called when the mouse button is clicked while positioned over the appropriate object.

How do you close a dropdown when clicking outside React? ›

Here we go: abandon stop propagation, go back to listening to the document object, and use the node. contains API to determine whether a click event happens outside the dropdown menu. If it does, hide the dropdown menu, since we need to use ref to save the DOM node in React in order to use the API.

How do I stop clicking outside React modal? ›

You can prevent closing of modal dialog by setting the beforeClose event argument cancel value to true.

Which JavaScript function is used to detect mouse clicks? ›

The MouseEvent button property is used to define the left or right click events.

What does .show do in JavaScript? ›

jQuery Effect show() Method

The show() method shows the hidden, selected elements. Note: show() works on elements hidden with jQuery methods and display:none in CSS (but not visibility:hidden).

How do you hide the element when you click outside? ›

To hide an element when clicked outside:
  1. Add a click event listener to the document object.
  2. On each click, check if the clicked element is outside of the specific element using the contains() method.
  3. If the clicked element is outside, hide the original element.

How do you make a div pop? ›

There are two steps to using a DIV as a popup box. First, you must create the DIV on your page (it can be invisible to start). Second, you need a script function to make the DIV appear & disappear and change it's contents and location. Click on the button to answer the questions.

How do you detect a click outside an element in Vue? ›

The way we're going to detect an outside click is by listening to a click event (and touchstart for mobiles) on the whole page ( document ) and then check if the element we clicked on is not the dialog or part of it.

How do you simulate a click on a div? ›

Method 1: Using the click() method. The click() method is used to simulate a mouse click on an element. It fires the click event of the element on which it is called. The event bubbles up to elements higher in the document tree and fires their click events also.

Are React hooks called every render? ›

Yes they are called on each render, in the first render it initialise a memory cell, on re-render it read the value of the current cell : When you call a Hook like useState(), it reads the current cell (or initializes it during the first render), and then moves the pointer to the next one.

When should you not use hooks? ›

Don't call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns. By following this rule, you ensure that Hooks are called in the same order each time a component renders.

Are Command hooks usable outside? ›

Climate and Temperature

The products hold strongly down to -20°F (-29°C). Can I use Command™ Products outside in hot climates? Yes you can with Command™ Outdoor Products. The products hold strongly up to 125°F (51°C).

How do we perceive or detect touch? ›

Cortical Maps and Sensitivity to Touch

Sensations begin as signals generated by touch receptors in your skin. They travel along sensory nerves made up of bundled fibers that connect to neurons in the spinal cord. Then signals move to the thalamus, which relays information to the rest of the brain.

Which sensor is used to detect the touch? ›

Touch sensors are also called as tactile sensors and are sensitive to touch, force or pressure. It can be implemented using Capacitive or Resistive sensing technology.

How do I track my mouse in React? ›

To get the position of the mouse in React, add a mousemove event handler to the window object and access the clientX and clientY properties of the MouseEvent object to get the X and Y coordinates of the mouse respectively. The current mouse position is displayed.

What is trigger (' click ')? ›

trigger( "click" ); As of jQuery 1.3, . trigger() ed events bubble up the DOM tree; an event handler can stop the bubbling by returning false from the handler or calling the . stopPropagation() method on the event object passed into the event.

How do I automatically trigger a button click after 5 seconds with react? ›

You could create a ref for the <button> and set a timeout inside of an effect hook to call the button click event after 5 seconds. You could throw in a state hook to limit the prompt. Used setInterval instead of setTimeout to retry every 5 seconds.

Can I use event listener in react? ›

When using React, you generally don't need to call addEventListener to add listeners to a DOM element after it is created. Instead, just provide a listener when the element is initially rendered. You have to be careful about the meaning of this in JSX callbacks. In JavaScript, class methods are not bound by default.

How do you trigger a button click? ›

To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery.

What control is used to generate a click event? ›

The Button control represents a standard Windows button. It is generally used to generate a Click event by providing a handler for the Click event.

Which method is invoked when a component is clicked? ›

The actionPerformed() method is invoked automatically whenever you click on the registered component.

What can I use instead of keypress? ›

Warning: Since this event has been deprecated, you should use beforeinput or keydown instead.

What is the difference between keydown and keypress events? ›

keydown – fires when any key is pressed down, fires first, and always before the browser processes the key (e.g. inserting text, moving focus, etc). keypress – fires when a key that produces a character value is pressed down, fires after keydown , and before the browser processes the key.

How do you check if Enter key is pressed in React JS? ›

In the input, we have added an on Keypress function which will get activated whenever the user clicks and types something in the input. It will not do anything since a condition is added. The condition is that for every keystroke it will check if the key is entered or not.

How does Vue detect click outside component? ›

Summary: Just declare a ref, point the ref to the template element and send it to the composable as first parameter. The second parameter of the composable is the callback what do you want to execute when clicked out. Happy Code!

How do I make dialog not close when I click outside? ›

By default, dialog can be closed by pressing Esc key and clicking the close icon on the right of dialog header. It can also be closed by clicking outside of the dialog using hide method. Set the CloseOnEscape property value to false to prevent closing of the dialog when pressing Esc key.

How do I make modal close on click outside Vue? ›

Close Dialog while Click on Outside of Dialog in Vue Dialog component. By default, dialog can be closed by pressing Esc key and clicking the close icon on the right of dialog header. It can also be closed by clicking outside of the dialog using hide method.

How does Vue work under the hood? ›

Under the hood Vue will walk through all the properties that we define into the data and converts them to getter/setters using Object. defineProperty. When any data property gets a new value then the set function will notify the Watchers. A Watcher is created for each component when a Vue application is initialized.

How do I hide the modal when I click outside? ›

Modal Header

You have two options to close this modal: Click on the "x" or click anywhere outside of the modal!


Top Articles
Latest Posts
Article information

Author: Catherine Tremblay

Last Updated: 07/26/2023

Views: 5973

Rating: 4.7 / 5 (47 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Catherine Tremblay

Birthday: 1999-09-23

Address: Suite 461 73643 Sherril Loaf, Dickinsonland, AZ 47941-2379

Phone: +2678139151039

Job: International Administration Supervisor

Hobby: Dowsing, Snowboarding, Rowing, Beekeeping, Calligraphy, Shooting, Air sports

Introduction: My name is Catherine Tremblay, I am a precious, perfect, tasty, enthusiastic, inexpensive, vast, kind person who loves writing and wants to share my knowledge and understanding with you.