use-outside-click-react-hook
v1.0.0
Published
React Hook for Handling Clicks and Touches Outside a Specified Element
Downloads
64
Maintainers
Readme
use-outside-click-react-hook
React Hook for Handling Clicks and Touches Outside a Specified Element (Only 3 code steps!).
Storybook:
https://shadiabuhilal.github.io/use-outside-click-react-hook/
Install
npm i use-outside-click-react-hook
Usage
import use-outside-click-react-hook
import useOutsideClick from 'use-outside-click-react-hook';
Using useOutsideClick
useOutsideClick React Hook
Example:
const [currentStepIndexState, setCurrentStepIndex] = useState(0);
...
export default function FooComponent() {
const [isOpenState, setIsOpenState] = useState(false);
// STEP1: Use ref to attach this functionality to the element that requires outside click and touch detection.
const menuPopupDivRef = useRef(null);
// STEP2: Use useOutsideClick React Hook to apply this functionality to the element that requires outside click and touch detection.
useOutsideClick(menuPopupDivRef, () => {
setIsOpenState(false);
});
return <div className='page-content'>
<button data-testid="btnMenu" onClick={()=> setIsOpenState(true)}>Menu</button>
{/* STEP3: Set ref to the element that requires outside click and touch detection */}
{isOpenState && <div ref={menuPopupDivRef} className='menu-popup'>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>}
</div>;
}
For more info, please check storybook