Skip to content

Instantly share code, notes, and snippets.

View Hat52's full-sized avatar
🎯
Focusing

Hamza Ali Hat52

🎯
Focusing
View GitHub Profile
@Hat52
Hat52 / useClickOutside.ts
Last active February 10, 2023 06:18
React Hook for Detecting Clicks Outside a Component: This is a simple and efficient way to detect clicks outside a React component. By using the MutableRefObject and useEffect hooks from React, you can easily listen to mousedown events on the document and trigger a callback function when a click outside of a component is detected. This is useful…
import { MutableRefObject, useEffect,useState } from 'react';
// Define the type for the hook, which takes two arguments: a reference to a component and a callback function
type OutsideNotifierHook = (
ref: MutableRefObject<any>, // The reference to the component
onOutsideClick: (isInside: false) => void // The callback function that will be triggered when a click outside of the component is detected
) => void;
// The implementation of the hook, which will be exported for use in other components