Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: dropdown menu handles clicking outside #353

Merged
merged 5 commits into from
Sep 5, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions components/Dropdown/dropdown.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,30 @@
import React, {useState} from 'react';
import React, {useState,useRef,useEffect} from 'react';

function Dropdown({ active, items, setOptions, setOptions2 }) {
const [show, setShow] = useState(false)
const dropdownRef = useRef(null);
useEffect(() => {
// This checks if the click event occurred outside the dropdown, if true we closes the dropdown.
function handleClickOutside(event) {
if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
setShow(false);
}
}
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, [dropdownRef]);
return (
<div class='relative inline-block w-full'>
<div class='relative inline-block w-full' ref={dropdownRef}>
<div className='w-full'>
<button
type='button'
className='flex justify-between text-white p-4 w-full justify-center gap-x-1.5 shadow-sm card-bg hover:bg-gray-50 gradient-bg no-border rounded-md'
id='menu-button'
aria-expanded='true'
aria-haspopup='true'
onClick={() => setShow(true)}
onClick={() => setShow(!show)}
>
<div>{active}</div>
<svg
Expand Down
Loading