Skip to content

Commit

Permalink
Close Combo Box when click outside (#227)
Browse files Browse the repository at this point in the history
  • Loading branch information
ZengLawrence authored Oct 31, 2024
1 parent ffa9088 commit 9694e13
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 5 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "diet-diary",
"version": "2.26.3",
"version": "2.26.4",
"private": true,
"homepage": ".",
"dependencies": {
Expand Down
22 changes: 20 additions & 2 deletions src/components/input-form/FoodDescriptionComboBox.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import _ from "lodash";
import { useEffect, useRef, useState } from "react";
import { RefObject, useEffect, useRef, useState } from "react";
import Dropdown from "react-bootstrap/Dropdown";
import Form from "react-bootstrap/Form";
import { Suggestion } from "../../features/suggestions/Suggestion";
Expand Down Expand Up @@ -62,6 +62,21 @@ interface Props {
updateFoodDescriptionServing: (desc: string, serving?: Serving, bestChoice?: boolean) => void;
}

function useClickOutside(ref: RefObject<HTMLDivElement>, handler: () => void) {
useEffect(() => {
function handleClickOutside(event: MouseEvent) {
if (ref.current && !ref.current.contains(event.target as Node)) {
handler();
}
}

document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, [ref, handler]);
}

export const FoodDescriptionComboBox = (props: Props) => {

const { invalid } = props;
Expand All @@ -82,8 +97,11 @@ export const FoodDescriptionComboBox = (props: Props) => {
if (invalid) { setToggle(false); }
}, [invalid]);

const ref = useRef<HTMLDivElement>(null);
useClickOutside(ref, () => setToggle(false));

return (
<Dropdown show={toggle} onSelect={() => setToggle(false)}>
<Dropdown ref={ref} show={toggle} onSelect={() => setToggle(false)}>

<Form.Label htmlFor="inputFoodDescription">Food description</Form.Label>
<Form.Control
Expand Down

0 comments on commit 9694e13

Please sign in to comment.