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

세그먼트 컨트롤(Segmented Control)

원문 보기 위키 갱신

각 세그먼트가 라디오 input으로 동작하는 두 개 이상의 세그먼트로 이루어진 선형 집합이며, 기본값이 필수예요.

출처: 문서

본문

Import

import { SegmentedControl } from "@kobalte/core/segmented-control";
// or
import { Root, Label, ... } from "@kobalte/core/segmented-control";

Features

  • WAI-ARIA Radio Group 디자인 패턴을 따라요.
  • 각 세그먼트는 시각적으로 숨겨진 네이티브 HTML <input> 요소로 만들어져 커스텀 스타일링을 할 수 있어요.
  • 폼 리셋 이벤트와 동기화돼요.
  • 보조 기술을 위한 그룹 및 세그먼트 라벨링을 지원해요.
  • 제어(controlled) 또는 비제어(uncontrolled) 방식으로 사용할 수 있어요.
  • 애니메이션 가능한 인디케이터를 지원해요.

Anatomy

세그먼트 컨트롤은 다음 요소들로 구성돼요:

  • SegmentedControl: 세그먼트 컨트롤의 루트 컨테이너예요.
  • SegmentedControl.Label: 세그먼트 컨트롤에 대한 정보를 사용자에게 주는 라벨이에요.
  • SegmentedControl.Description: 세그먼트 컨트롤에 대한 더 많은 정보를 사용자에게 주는 설명이에요.
  • SegmentedControl.ErrorMessage: 세그먼트 컨트롤의 유효성 검사 오류를 해결하는 방법을 사용자에게 알려주는 오류 메시지예요.
  • SegmentedControl.Indicator: 항목 아래에 표시되어 선택된 항목을 나타내는 시각적 인디케이터예요.

세그먼트 컨트롤 항목은 다음 요소들로 구성돼요:

  • SegmentedControl.Item: 항목의 라디오 버튼 루트 컨테이너예요.
  • SegmentedControl.ItemInput: 항목의 라디오 버튼 안에 시각적으로 숨겨진 네이티브 html input이에요.
  • SegmentedControl.ItemControl: 항목의 라디오 버튼을 시각적으로 나타내는 요소예요.
  • SegmentedControl.ItemIndicator: 항목의 라디오 버튼이 체크된 상태일 때 렌더링되는 시각적 인디케이터예요.
  • SegmentedControl.ItemLabel: 항목의 라디오 버튼에 대한 정보를 사용자에게 주는 라벨이에요.
  • SegmentedControl.ItemDescription: 항목의 라디오 버튼에 대한 더 많은 정보를 사용자에게 주는 설명이에요.
<SegmentedControl>
	<SegmentedControl.Label />
	<SegmentedControl.Indicator />
	<SegmentedControl.Item>
		<SegmentedControl.ItemInput />
		<SegmentedControl.ItemControl>
			<SegmentedControl.ItemIndicator />
		</SegmentedControl.ItemControl>
		<SegmentedControl.ItemLabel />
		<SegmentedControl.ItemDescription />
	</SegmentedControl.Item>
	<SegmentedControl.Description />
	<SegmentedControl.ErrorMessage />
</SegmentedControl>

Example

Usage

role="presentation"은 Chromium 계열 브라우저의 버그(의미론을 잘못 파싱해 스크린 리더를 깨뜨리는 문제) 때문에 SegmentedControl과 SegmentedControl.Item 사이의 모든 비-콘텐츠 요소에 필요해요.

Controlled value

각 라디오의 value prop에 대응하는 값을 받는 value prop을 사용해 값을 제어(controlled) 방식으로 만들 수 있어요. 사용자가 라디오를 선택하면 onChange 이벤트가 발생하며 새 값을 받아요.

import { createSignal } from "solid-js";

function ControlledExample() {
	const [value, setValue] = createSignal("Orange");

	return (
		<>
			<SegmentedControl value={value()} onChange={setValue}>
				<SegmentedControl.Label>Favorite fruit</SegmentedControl.Label>
				<div role="presentation">
					<SegmentedControl.Indicator />
					<div role="presentation">
						<For each={["Apple", "Orange", "Watermelon"]}>
							{fruit => (
								<SegmentedControl.Item value={fruit}>
									<SegmentedControl.ItemInput />
									<SegmentedControl.ItemLabel>{fruit}</SegmentedControl.ItemLabel>
								</SegmentedControl.Item>
							)}
						</For>
					</div>
				</div>
			</SegmentedControl>
			<p class="not-prose text-sm mt-4">Your favorite fruit is: {value()}.</p>
		</>
	);
}

Description

SegmentedControl.Description 컴포넌트를 사용해 세그먼트 컨트롤에 추가 도움말 텍스트를 연결할 수 있어요.

<SegmentedControl defaultValue="Apple">
	<SegmentedControl.Label>Favorite fruit</SegmentedControl.Label>
	<div role="presentation">
		<SegmentedControl.Indicator />
		<div role="presentation">
			<For each={["Apple", "Orange", "Watermelon"]}>
				{fruit => <SegmentedControl.Item value={fruit}>...</SegmentedControl.Item>}
			</For>
		</div>
	</div>
	<SegmentedControl.Description>Choose the fruit you like the most.</SegmentedControl.Description>
</SegmentedControl>

Error message

SegmentedControl.ErrorMessage 컴포넌트를 사용해 사용자가 유효성 검사 오류를 해결하도록 도울 수 있어요. 보조 기술에 세그먼트 컨트롤을 의미적으로 유효하지 않음으로 표시하기 위해 validationState prop과 함께 사용해야 해요.

기본적으로 validationState prop이 invalid로 설정된 경우에만 렌더링돼요. 오류 메시지를 항상 렌더링하려면 forceMount prop을 사용해요(ex: 애니메이션 라이브러리와 함께 사용할 때).

import { createSignal } from "solid-js";

function ErrorMessageExample() {
	const [value, setValue] = createSignal("Orange");

	return (
		<SegmentedControl
			value={value()}
			onChange={setValue}
			validationState={value() !== "Apple" ? "invalid" : "valid"}
		>
			<SegmentedControl.Label>Favorite fruit</SegmentedControl.Label>
			<div role="presentation">
				<SegmentedControl.Indicator />
				<div role="presentation">
					<For each={["Apple", "Orange", "Watermelon"]}>
						{fruit => <SegmentedControl.Item value={fruit}>...</SegmentedControl.Item>}
					</For>
				</div>
			</div>
			<SegmentedControl.ErrorMessage>Hmm, I prefer apples.</SegmentedControl.ErrorMessage>
		</SegmentedControl>
	);
}

HTML forms

세그먼트 컨트롤의 name prop을 항목의 라디오 value prop과 함께 사용해 HTML 폼과 통합할 수 있어요.

function HTMLFormExample() {
	const onSubmit = (e: SubmitEvent) => {
		// handle form submission.
	};

	return (
		<form onSubmit={onSubmit}>
			<SegmentedControl name="favorite-fruit" defaultValue="Orange">
				<SegmentedControl.Label>Favorite fruit</SegmentedControl.Label>
				<div role="presentation">
					<SegmentedControl.Indicator />
					<div role="presentation">
						<For each={["Apple", "Orange", "Watermelon"]}>
							{fruit => <SegmentedControl.Item value={fruit}>...</SegmentedControl.Item>}
						</For>
					</div>
				</div>
			</SegmentedControl>
			<div>
				<button type="reset">Reset</button>
				<button type="submit">Submit</button>
			</div>
		</form>
	);
}

Orientation

세그먼트 컨트롤의 orientation prop을 사용해 세그먼트 컨트롤의 방향을 변경할 수 있어요.

<SegmentedControl orientation="vertical" defaultValue="Apple">
	<SegmentedControl.Label>Favorite fruit</SegmentedControl.Label>
	<div role="presentation">
		<SegmentedControl.Indicator />
		<div role="presentation">
			<For each={["Apple", "Orange", "Watermelon"]}>
				{fruit => <SegmentedControl.Item value={fruit}>...</SegmentedControl.Item>}
			</For>
		</div>
	</div>
	<SegmentedControl.Description>Choose the fruit you like the most.</SegmentedControl.Description>
</SegmentedControl>

API Reference

SegmentedControl

SegmentedControl은 @kobalte/core/segmented-control의 Root import와 동일해요.

Prop Description
value string
The controlled value of the item's radio button to check.
defaultValue string
The value of the item's radio button that should be checked when initially rendered. Useful when you do not need to control the state of the radio buttons.
onChange (value: string) => void
Event handler called when the value changes.
orientation 'horizontal' | 'vertical'
The axis the segmented control items should align with.
name string
The name of the segmented control. Submitted with its owning form as part of a name/value pair.
validationState 'valid' | 'invalid'
Whether the segmented control should display its "valid" or "invalid" visual styling.
required boolean
Whether the user must check a segmented control item before the owning form can be submitted.
disabled boolean
Whether the segmented control is disabled.
readOnly boolean
Whether the segmented control items can be selected but not changed by the user.
Data attribute Description
data-valid Present when the segmented control is valid according to the validation rules.
data-invalid Present when the segmented control is invalid according to the validation rules.
data-required Present when the user must check a segmented control item before the owning form can be submitted.
data-disabled Present when the segmented control is disabled.
data-readonly Present when the segmented control is read only.

SegmentedControl.Label, SegmentedControl.Description and SegmentedControl.ErrorMessage shares the same data-attributes.

SegmentedControl.ErrorMessage

Prop Description
forceMount boolean
Used to force mounting when more control is needed. Useful when controlling animation with SolidJS animation libraries.

SegmentedControl.Item

Prop Description
value string
The value of the item's radio button, used when submitting an HTML form. See MDN.
disabled boolean
Whether the item's radio button is disabled or not.
Data attribute Description
data-valid Present when the parent segmented control is valid according to the validation rules.
data-invalid Present when the parent segmented control is invalid according to the validation rules.
data-checked Present when the segmented control checked.
data-disabled Present when the segmented control disabled.

SegmentedControl.ItemInput, SegmentedControl.ItemControl, SegmentedControl.ItemIndicator and SegmentedControl.ItemLabel shares the same data-attributes.

SegmentedControl.ItemIndicator

Prop Description
forceMount boolean
Used to force mounting when more control is needed. Useful when controlling animation with SolidJS animation libraries.

Rendered elements

Component Default rendered element
SegmentedControl div
SegmentedControl.Label span
SegmentedControl.Description div
SegmentedControl.ErrorMessage div
SegmentedControl.Indicator div
SegmentedControl.Item div
SegmentedControl.ItemInput input
SegmentedControl.ItemControl div
SegmentedControl.ItemIndicator div
SegmentedControl.ItemLabel label
SegmentedControl.ItemDescription div

Accessibility

Keyboard Interactions

Key Description
Tab Moves focus to either the checked item's radio button or the first item's radio button in the group.
Space When focus is on an unchecked item's radio button, checks it.
ArrowDown Moves focus and checks the next item's radio button in the group.
ArrowRight Moves focus and checks the next item's radio button in the group.
ArrowUp Moves focus and checks the previous item's radio button in the group.
ArrowLeft Moves focus and checks the previous item's radio button in the group.

더 알아보기 (Learn more)