2021-09-24
1730
#react
Shalitha Suranga
67554
Sep 24, 2021 â‹… 6 min read

How to detect a click outside a React component

Shalitha Suranga Programmer | Author of Neutralino.js | Technical Writer

Recent posts:

master state management hydration Nuxt usestate

Nuxt state management and hydration with useState

useState can effectively replace ref in many scenarios and prevent Nuxt hydration mismatches that can lead to unexpected behavior and errors.

Yan Sun
Jan 20, 2025 â‹… 8 min read
React Native List Components: FlashList, FlatList, And More

React Native list components: FlashList, FlatList, and more

Explore the evolution of list components in React Native, from `ScrollView`, `FlatList`, `SectionList`, to the recent `FlashList`.

Chimezie Innocent
Jan 16, 2025 â‹… 4 min read
Building An AI Agent For Your Frontend Project

Building an AI agent for your frontend project

Explore the benefits of building your own AI agent from scratch using Langbase, BaseUI, and Open AI, in a demo Next.js project.

Ivaylo Gerchev
Jan 15, 2025 â‹… 12 min read
building UI sixty seconds shadcn framer ai

Building a UI in 60 seconds with Shadcn and Framer AI

Demand for faster UI development is skyrocketing. Explore how to use Shadcn and Framer AI to quickly create UI components.

Peter Aideloje
Jan 14, 2025 â‹… 6 min read
View all posts

4 Replies to "How to detect a click outside a React component"

  1. Be careful.
    The first example using useEffect without dependencies array (it should be [handleClickOutside] or []) will be called on each render.
    The second one using class is wrong, .bind(this) creates a new reference and the listener will never be removed on componentWillUnmount.
    Use fat arrow function or binding on constructor, but never use .bind for events listeners !

    1. Thank you very much for these great suggestions. I updated code with binding in constructor. Also, I improved the hook-based example code by destructing props and putting handleClickOutside into useEffect as recommended in React Hooks FAQ docs.

  2. Is there a way to make it so the tooltip disappears when you click on either button or the component after already clicking it

Leave a Reply