본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Dropdown Menu (드롭다운 메뉴)

원문 보기 위키 갱신

버튼으로 트리거되는 메뉴를 사용자에게 표시하는 컴포넌트예요. 서브메뉴, 체크 가능한 항목, 라디오 그룹을 지원해요.

출처: 문서

본문

임포트 (Import)

import { DropdownMenu } from "@kobalte/core/dropdown-menu";
// or
import { Root, Trigger, ... } from "@kobalte/core/dropdown-menu";
// or (deprecated)
import { DropdownMenu } from "@kobalte/core";

기능 (Features)

  • WAI-ARIA Menu Button 디자인 패턴을 사용해 보조 기술에 메뉴가 있는 버튼으로 노출돼요.
  • 모달(modal) 및 비모달(non-modal) 모드를 지원해요.
  • 서브메뉴를 지원해요.
  • 항목, 라벨, 항목 그룹을 지원해요.
  • 선택적 불확정(indeterminate) 상태를 가진 체크 가능한 항목(단일 또는 다중)을 지원해요.
  • 비활성 항목을 지원해요.
  • 접근성을 위한 복잡한 항목 라벨링을 지원해요.
  • 키보드 열기 및 탐색을 지원해요.
  • 키보드 탐색 중 자동 스크롤을 지원해요.
  • 텍스트를 타이핑해 항목에 포커스할 수 있는 타입어헤드(typeahead)를 제공해요.
  • 선택적으로 가리키는 화살표를 렌더링할 수 있어요.
  • 포커스는 완전히 관리돼요.
  • 제어(controlled) 또는 비제어(uncontrolled) 방식으로 사용할 수 있어요.

구조 (Anatomy)

드롭다운 메뉴는 다음 요소로 구성돼요.

  • DropdownMenu: 드롭다운 메뉴의 루트 컨테이너예요.
  • DropdownMenu.Trigger: 메뉴를 토글하는 버튼이에요.
  • DropdownMenu.Icon: 메뉴 트리거 옆에 자주 표시되며 열릴 수 있다는 시각적 단서를 주는 작은 아이콘이에요.
  • DropdownMenu.Portal: 메뉴가 열렸을 때 자식들을 body로 포털(portal)해요.
  • DropdownMenu.Content: 메뉴가 열렸을 때 렌더링될 콘텐츠를 포함해요.
  • DropdownMenu.Arrow: 메뉴 콘텐츠 옆에 렌더링할 선택적 화살표 요소예요.
  • DropdownMenu.Separator: 메뉴에서 항목을 시각적으로 구분하는 데 사용돼요.
  • DropdownMenu.Group: 여러 항목을 그룹화하는 데 사용돼요. 자동 라벨링을 통한 좋은 접근성을 위해 DropdownMenu.GroupLabel과 함께 사용하세요.
  • DropdownMenu.GroupLabel: 그룹의 라벨을 렌더링하는 데 사용돼요. 화살표 키로 포커스할 수 없어요.
  • DropdownMenu.Sub: 서브메뉴의 모든 부분을 포함해요.
  • DropdownMenu.SubTrigger: 서브메뉴를 여는 항목이에요. DropdownMenu.Sub 안에 렌더링해야 해요.
  • DropdownMenu.SubContent: 서브메뉴가 열렸을 때 튀어나오는 컴포넌트예요. DropdownMenu.Sub 안에 렌더링해야 해요.

메뉴 항목은 다음 요소로 구성돼요.

  • DropdownMenu.Item: 선택(select)의 항목이에요.
  • DropdownMenu.ItemLabel: 항목에 대해 공지될 접근 가능한 라벨이에요.
  • DropdownMenu.ItemDescription: 항목에 대해 공지될 선택적 접근 가능한 설명이에요.
  • DropdownMenu.ItemIndicator: 항목이 체크됐을 때 렌더링되는 시각적 표시예요.

체크 가능한 메뉴 항목은 다음 요소로 구성돼요.

  • DropdownMenu.RadioGroup: 여러 DropdownMenu.RadioItem을 그룹화하고 선택을 관리하는 데 사용돼요.
  • DropdownMenu.RadioItem: 라디오처럼 제어·렌더링할 수 있는 항목이에요.
  • DropdownMenu.CheckboxItem: 체크박스처럼 제어·렌더링할 수 있는 항목이에요.
<DropdownMenu>
	<DropdownMenu.Trigger>
		<DropdownMenu.Icon />
	</DropdownMenu.Trigger>

	<DropdownMenu.Portal>
		<DropdownMenu.Content>
			<DropdownMenu.Arrow />

			<DropdownMenu.Item>
				<DropdownMenu.ItemLabel />
				<DropdownMenu.ItemDescription />
			</DropdownMenu.Item>

			<DropdownMenu.Group>
				<DropdownMenu.GroupLabel />
				<DropdownMenu.Item />
			</DropdownMenu.Group>

			<DropdownMenu.CheckboxItem>
				<DropdownMenu.ItemIndicator />
			</DropdownMenu.CheckboxItem>

			<DropdownMenu.RadioGroup>
				<DropdownMenu.RadioItem>
					<DropdownMenu.ItemIndicator />
				</DropdownMenu.RadioItem>
			</DropdownMenu.RadioGroup>

			<DropdownMenu.Sub>
				<DropdownMenu.SubTrigger />
				<DropdownMenu.Portal>
					<DropdownMenu.SubContent />
				</DropdownMenu.Portal>
			</DropdownMenu.Sub>

			<DropdownMenu.Separator />
		</DropdownMenu.Content>
	</DropdownMenu.Portal>
</DropdownMenu>

예제 (Example)

기본 예제는 공식 문서 페이지에서 확인할 수 있어요.

사용법 (Usage)

기본 열림 (Default open)

비제어 상태의 초기 열림 값은 defaultOpen prop으로 제공할 수 있어요.

<DropdownMenu defaultOpen>...</DropdownMenu>

제어된 열림 (Controlled open)

open prop을 사용해 열림 상태를 제어할 수 있어요. 사용자가 트리거, 항목을 누르거나 외부와 상호작용하면 onOpenChange 이벤트가 발생하며 새 값을 받아요.

import { createSignal } from "solid-js";

function ControlledExample() {
	const [open, setOpen] = createSignal(false);

	return (
		<DropdownMenu open={open()} onOpenChange={setOpen}>
			<DropdownMenu.Trigger>{open() ? "Close" : "Open"}</DropdownMenu.Trigger>
			<DropdownMenu.Portal>
				<DropdownMenu.Content>...</DropdownMenu.Content>
			</DropdownMenu.Portal>
		</DropdownMenu>
	);
}

원점 인식 애니메이션 (Origin-aware animations)

CSS 사용자 정의 속성 --kb-menu-content-transform-origin을 노출해서 콘텐츠를 계산된 원점에서 애니메이션할 수 있어요.

/* style.css */
.dropdown-menu__content,
.dropdown-menu__sub-content {
	transform-origin: var(--kb-menu-content-transform-origin);
	animation: contentHide 250ms ease-in forwards;
}

.dropdown-menu__content[data-expanded],
.dropdown-menu__sub-content[data-expanded] {
	animation: contentShow 250ms ease-out;
}

@keyframes contentShow {
	from {
		opacity: 0;
		transform: scale(0.96);
	}
	to {
		opacity: 1;
		transform: scale(1);
	}
}

@keyframes contentHide {
	from {
		opacity: 1;
		transform: scale(1);
	}
	to {
		opacity: 0;
		transform: scale(0.96);
	}
}

API 참조 (API Reference)

DropdownMenu는 @kobalte/core/dropdown-menu의 Root 임포트(그리고 더 이상 사용되지 않는 DropdownMenu.Root)와 동일해요.

Prop Description
open boolean
The controlled open state of the menu.
defaultOpen boolean
The default open state when initially rendered. Useful when you do not need to control the open state.
onOpenChange (open: boolean) => void
Event handler called when the open state of the menu changes.
id string
A unique identifier for the component. The id is used to generate id attributes for nested components. If no id prop is provided, a generated id will be used.
modal boolean
Whether the menu should be the only visible content for screen readers, when set to true:
- interaction with outside elements will be disabled.
- scroll will be locked.
- focus will be locked inside the menu content.
- elements outside the menu content will not be visible for screen readers.
preventScroll boolean
Whether the scroll should be locked even if the menu is not modal.
forceMount boolean
Used to force mounting the menu (portal and content) when more control is needed. Useful when controlling animation with SolidJS animation libraries.

DropdownMenu는 DropdownMenu.Content의 배치를 커스터마이즈하기 위한 다음 prop들도 받아요.

Prop Description
getAnchorRect (anchor?: HTMLElement) => AnchorRect | undefined
Function that returns the trigger element's DOMRect.
placement Placement
The placement of the menu content.
gutter number
The distance between the menu content and the trigger element. By default, it's 0 plus half of the arrow offset, if it exists.
shift number
The skidding of the menu content along the trigger element.
flip boolean | string
Controls the behavior of the menu content when it overflows the viewport:
- If a boolean, specifies whether the menu content should flip to the opposite side when it overflows.
- If a string, indicates the preferred fallback placements when it overflows.
The placements must be spaced-delimited, e.g. "top left".
slide boolean
Whether the menu content should slide when it overflows.
overlap boolean
Whether the menu content can overlap the trigger element when it overflows.
sameWidth boolean
Whether the menu content should have the same width as the trigger element. This will be exposed to CSS as --kb-popper-anchor-width.
fitViewport boolean
Whether the menu content should fit the viewport. If this is set to true, the menu content will have maxWidth and maxHeight set to the viewport size. This will be exposed to CSS as --kb-popper-content-available-width and --kb-popper-content-available-height.
hideWhenDetached boolean
Whether to hide the menu content when the trigger element becomes occluded.
detachedPadding number
The minimum padding in order to consider the trigger element occluded.
arrowPadding number
The minimum padding between the arrow and the menu content corner.
overflowPadding number
The minimum padding between the menu content and the viewport edge. This will be exposed to CSS as --kb-popper-overflow-padding.

DropdownMenu.Trigger는 Button으로 구성돼요.

Data attribute Description
data-expanded Present when the menu is open.
data-closed Present when the menu is close.

DropdownMenu.Icon, DropdownMenu.Content, DropdownMenu.SubTrigger 및 DropdownMenu.SubContent는 동일한 data-attributes를 공유해요.

popper positioner는 DropdownMenu.Content와 동일한 z-index를 복사해요.

Prop Description
onOpenAutoFocus (event: Event) => void
Event handler called when focus moves into the component after opening. It can be prevented by calling event.preventDefault.
onCloseAutoFocus (event: Event) => void
Event handler called when focus moves to the trigger after closing. It can be prevented by calling event.preventDefault.
onEscapeKeyDown (event: KeyboardEvent) => void
Event handler called when the escape key is down. It can be prevented by calling event.preventDefault.
onPointerDownOutside (event: PointerDownOutsideEvent) => void
Event handler called when a pointer event occurs outside the bounds of the component. It can be prevented by calling event.preventDefault.
onFocusOutside (event: FocusOutsideEvent) => void
Event handler called when the focus moves outside the bounds of the component. It can be prevented by calling event.preventDefault.
onInteractOutside (event: InteractOutsideEvent) => void
Event handler called when an interaction (pointer or focus event) happens outside the bounds of the component. It can be prevented by calling event.preventDefault.
Prop Description
size number
The size of the arrow.
Prop Description
textValue string
Optional text used for typeahead purposes. By default, the typeahead behavior will use the .textContent of the DropdownMenu.ItemLabel part if provided, or fallback to the .textContent of the DropdownMenu.Item. Use this when the content is complex, or you have non-textual content inside.
disabled boolean
Whether the item is disabled or not.
closeOnSelect boolean
Whether the menu should close when the item is activated.
onSelect () => void
Event handler called when the user selects an item (via mouse or keyboard).
Data attribute Description
data-disabled Present when the item is disabled.
data-highlighted Present when the item is highlighted.

DropdownMenu.ItemLabel, DropdownMenu.ItemDescription 및 DropdownMenu.ItemIndicator는 동일한 data-attributes를 공유해요.

Prop Description
forceMount boolean
Used to force mounting when more control is needed. Useful when controlling animation with SolidJS animation libraries.
Prop Description
value string
The controlled value of the menu radio item to check.
defaultValue string
The value of the menu radio item that should be checked when initially rendered. Useful when you do not need to control the state of the radio group.
onChange (value: string) => void
Event handler called when the value changes.
disabled boolean
Whether the radio group is disabled or not.
Prop Description
value string
The value of the menu item radio.
textValue string
Optional text used for typeahead purposes. By default, the typeahead behavior will use the .textContent of the DropdownMenu.ItemLabel part if provided, or fallback to the .textContent of the DropdownMenu.Item. Use this when the content is complex, or you have non-textual content inside.
disabled boolean
Whether the item is disabled or not.
closeOnSelect boolean
Whether the menu should close when the item is checked.
onSelect () => void
Event handler called when the user selects an item (via mouse or keyboard).
Data attribute Description
data-disabled Present when the item is disabled.
data-checked Present when the item is checked.
data-highlighted Present when the item is highlighted.
Prop Description
checked boolean
The controlled checked state of the item.
defaultChecked boolean
The default checked state when initially rendered. Useful when you do not need to control the checked state.
onChange (checked: boolean) => void
Event handler called when the checked state of the item changes.
textValue string
Optional text used for typeahead purposes. By default, the typeahead behavior will use the .textContent of the DropdownMenu.ItemLabel part if provided, or fallback to the .textContent of the DropdownMenu.Item. Use this when the content is complex, or you have non-textual content inside.
indeterminate boolean
Whether the item is in an indeterminate state.
disabled boolean
Whether the item is disabled or not.
closeOnSelect boolean
Whether the menu should close when the item is checked/unchecked.
onSelect () => void
Event handler called when the user selects an item (via mouse or keyboard).
Data attribute Description
data-disabled Present when the item is disabled.
data-indeterminate Present when the item is in an indeterminate state.
data-checked Present when the item is checked.
data-highlighted Present when the item is highlighted.
Prop Description
open boolean
The controlled open state of the sub menu.
defaultOpen boolean
The default open state when initially rendered. Useful when you do not need to control the open state.
onOpenChange (open: boolean) => void
Event handler called when the open state of the sub menu changes.

DropdownMenu.Sub는 DropdownMenu.SubContent의 배치를 커스터마이즈하기 위한 다음 prop들도 받아요.

Prop Description
getAnchorRect (anchor?: HTMLElement) => AnchorRect | undefined
Function that returns the trigger element's DOMRect.
gutter number
The distance between the sub menu content and the trigger element. By default, it's 0 plus half of the arrow offset, if it exists.
shift number
The skidding of the sub menu content along the trigger element.
slide boolean
Whether the sub menu content should slide when it overflows.
overlap boolean
Whether the sub menu content can overlap the trigger element when it overflows.
fitViewport boolean
Whether the sub menu content should fit the viewport. If this is set to true, the sub menu content will have maxWidth and maxHeight set to the viewport size. This will be exposed to CSS as --kb-popper-content-available-width and --kb-popper-content-available-height.
hideWhenDetached boolean
Whether to hide the sub menu content when the trigger element becomes occluded.
detachedPadding number
The minimum padding in order to consider the trigger element occluded.
arrowPadding number
The minimum padding between the arrow and the sub menu content corner.
overflowPadding number
The minimum padding between the sub menu content and the viewport edge. This will be exposed to CSS as --kb-popper-overflow-padding.
Prop Description
textValue string
Optional text used for typeahead purposes. By default, the typeahead behavior will use the .textContent of the DropdownMenu.SubTrigger. Use this when the content is complex, or you have non-textual content inside.
disabled boolean
Whether the sub menu trigger is disabled or not.
Data attribute Description
data-disabled Present when the item is disabled.
data-highlighted Present when the item is highlighted.
Prop Description
onEscapeKeyDown (event: KeyboardEvent) => void
Event handler called when the escape key is down. It can be prevented by calling event.preventDefault.
onPointerDownOutside (event: PointerDownOutsideEvent) => void
Event handler called when a pointer event occurs outside the bounds of the component. It can be prevented by calling event.preventDefault.
onFocusOutside (event: FocusOutsideEvent) => void
Event handler called when the focus moves outside the bounds of the component. It can be prevented by calling event.preventDefault.
onInteractOutside (event: InteractOutsideEvent) => void
Event handler called when an interaction (pointer or focus event) happens outside the bounds of the component. It can be prevented by calling event.preventDefault.

렌더링 요소 (Rendered elements)

Component Default rendered element
DropdownMenu none
DropdownMenu.Trigger button
DropdownMenu.Icon span
DropdownMenu.Portal Portal
DropdownMenu.Content div
DropdownMenu.Arrow div
DropdownMenu.Separator hr
DropdownMenu.Group div
DropdownMenu.GroupLabel span
DropdownMenu.Sub none
DropdownMenu.SubTrigger div
DropdownMenu.SubContent div
DropdownMenu.Item div
DropdownMenu.ItemLabel div
DropdownMenu.ItemDescription div
DropdownMenu.ItemIndicator div
DropdownMenu.RadioGroup div
DropdownMenu.RadioItem div
DropdownMenu.CheckboxItem div

접근성 (Accessibility)

키보드 상호작용 (Keyboard Interactions)

Key Description
Space When focus is on the trigger, opens the menu and focuses the first item.
When focus is on an item, activates the item.
Enter When focus is on the trigger, opens the menu and focuses the first item.
When focus is on an item, activates the item.
ArrowDown When focus is on the trigger, opens the menu and focuses the first item.
When focus is on an item, moves focus to the next item.
ArrowUp When focus is on the trigger, opens the menu and focuses the last item.
When focus is on an item, moves focus to the previous item.
ArrowRight / ArrowLeft When focus is on a sub menu trigger, opens or closes the submenu depending on reading direction.
Home When focus is on an item, moves focus to first item.
End When focus is on an item, moves focus to last item.
Esc Closes the menu and moves focus to the trigger.

더 알아보기 (Learn more)