Skip to content

Commit

Permalink
make dropdown close on click outside
Browse files Browse the repository at this point in the history
  • Loading branch information
myix765 committed Nov 15, 2024
1 parent ba974d7 commit 496ddb0
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions src/components/Dropdown/Dropdown.jsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,30 @@
import { useState } from 'react';
import { useState, useEffect, useRef } from 'react';
import { IoChevronDownOutline } from "react-icons/io5";

const Dropdown = ({ label, children, buttonClassName = "dropdown-button text-right" }) => {
const dropdownRef = useRef(null)
const [isOpen, setIsOpen] = useState(false);

// close dropdown when clicking outside of it
useEffect(() => {
const handleClickOutside = (e) => {
if (dropdownRef.current && !dropdownRef.current.contains(e.target)) {
setIsOpen(false)
}
}

if (isOpen) {
document.addEventListener('mousedown', handleClickOutside)
}
return () => {
// unbind event listener when dropdown is closed
document.removeEventListener('mousedown', handleClickOutside)
}
}, [isOpen])

return (
<div className="relative">
<div ref={dropdownRef} className="relative">
{/* dropdown button */}
<button
className={buttonClassName}
onClick={() => setIsOpen(!isOpen)}
Expand All @@ -14,6 +33,7 @@ const Dropdown = ({ label, children, buttonClassName = "dropdown-button text-rig
{label}
<IoChevronDownOutline className={`h-4 w-4 text-gray-500 transition-transform duration-200 ${isOpen ? 'rotate-180' : ''}`} />
</button>
{/* dropdown */}
{isOpen && (
<div className="absolute mt-2 w-full rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5 z-50">
<div className="py-1" role="menu" aria-orientation="vertical">
Expand Down

0 comments on commit 496ddb0

Please sign in to comment.