RahmanC / react-click-outside

The react-click-outside package provides a custom React hook for detecting clicks outside of a specified element. This hook simplifies the process of implementing common UI patterns such as closing a modal or dropdown when a user clicks outside of it.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

react-click-outside

How to use it?

You can use the hook this way:

Install

# with npm
npm install react-click-outside

# with yarn
yarn add react-click-outside

Usage

  • Import useRef, useState and the package in your app:
import {useRef, useState} from "react";
import {useOnClickOutside} from 'react-click-outside';
  • Declare useState and useRef hooks in your component:
const [showModal, setShowModal] = useState(false)
const ref = useRef(null);
  • Use the useOnClickOutside hook to handle clicks outside of a specific element:
 useOnClickOutside(ref, () => setShowModal(false));

Here, ref is a reference to the element that you want to track clicks outside of, and setShowModal(false) is the action you want to trigger when a click occurs outside of that element, in this case, closing a modal.

By following these steps, you can easily incorporate the useOnClickOutside hook into your React components to handle click events outside of specified elements.

About

The react-click-outside package provides a custom React hook for detecting clicks outside of a specified element. This hook simplifies the process of implementing common UI patterns such as closing a modal or dropdown when a user clicks outside of it.


Languages

Language:TypeScript 52.8%Language:JavaScript 47.2%