Skip to content

Commit d0f087a

Browse files
committed
Hide select's options if the user clicked outside of its body
1 parent a6ad73a commit d0f087a

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

packages/ui/components/select/select.tsx

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
import { DocumentEventListener } from "@solid-primitives/event-listener";
2+
import { RiArrowsArrowDropDownLine } from "solid-icons/ri";
13
import { Show, createSignal } from "solid-js";
24
import { JSX } from "solid-js/jsx-runtime";
3-
import { RiArrowsArrowDropDownLine } from "solid-icons/ri";
5+
import hasParentWithCondition from "../../../utils/hasParentWithCondition.ts";
46
import { SelectContextProvider } from "./context.ts";
57

68
type Props<V> = {
@@ -14,6 +16,7 @@ type Props<V> = {
1416

1517
export default function Select<V>(props: Props<V>) {
1618
const [optionsVisible, setOptionsVisible] = createSignal(false);
19+
let rootElement: HTMLDivElement;
1720

1821
function open() {
1922
setOptionsVisible(true);
@@ -33,8 +36,19 @@ export default function Select<V>(props: Props<V>) {
3336
}
3437
}
3538

39+
function onDocumentMouseDown(ev: MouseEvent) {
40+
const clickedInsideSelect = hasParentWithCondition(
41+
ev.target as Element,
42+
(element) => element === rootElement,
43+
);
44+
45+
if (!clickedInsideSelect) {
46+
close();
47+
}
48+
}
49+
3650
return (
37-
<div class="relative w-full">
51+
<div ref={rootElement!} class="relative w-full">
3852
<div
3953
class={`bg-gray-0 active:bg-gray-100 border border-gray-200 h-[35px] ${
4054
optionsVisible() ? "rounded-t-md" : "rounded-md"
@@ -49,6 +63,8 @@ export default function Select<V>(props: Props<V>) {
4963

5064
<SelectContextProvider onChange={props.onChange} onClose={close}>
5165
<Show when={optionsVisible()}>
66+
<DocumentEventListener onMousedown={onDocumentMouseDown} />
67+
5268
<div class="absolute w-full z-10 border border-gray-200 -mt-[1px] rounded-b-md overflow-hidden">
5369
{props.children}
5470
</div>

0 commit comments

Comments
 (0)