체크박스 그룹
체크박스 그룹 (Checkbox Group)
일련의 체크박스에 공유 상태를 제공하는 고품질의 비스타일 React 체크박스 그룹 컴포넌트예요.
본문
데모 (Demo)
Tailwind
이 예시는 Tailwind CSS로 컴포넌트를 구현하는 방법을 보여줘요.
/* index.tsx */
'use client';
import * as React from 'react';
import { Checkbox } from '@base-ui/react/checkbox';
import { CheckboxGroup } from '@base-ui/react/checkbox-group';
export default function ExampleCheckboxGroup() {
const id = React.useId();
return (
<CheckboxGroup
aria-labelledby={id}
defaultValue={['fuji-apple']}
className="flex flex-col items-start gap-1 text-neutral-950 dark:text-white"
>
<div className="text-sm font-bold" id={id}>
Apples
</div>
<label className="flex items-center gap-2 text-sm font-normal text-neutral-950 dark:text-white">
<Checkbox.Root
name="apple"
value="fuji-apple"
className="flex size-4 shrink-0 items-center justify-center border rounded-none p-0 border-neutral-950 bg-white text-white dark:border-white dark:bg-neutral-950 dark:text-neutral-950 data-checked:bg-neutral-950 data-checked:text-white dark:data-checked:bg-white dark:data-checked:text-neutral-950 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-950 dark:focus-visible:outline-white"
>
<Checkbox.Indicator className="flex data-unchecked:hidden">
<CheckIcon />
</Checkbox.Indicator>
</Checkbox.Root>
Fuji
</label>
<label className="flex items-center gap-2 text-sm font-normal text-neutral-950 dark:text-white">
<Checkbox.Root
name="apple"
value="gala-apple"
className="flex size-4 shrink-0 items-center justify-center border rounded-none p-0 border-neutral-950 bg-white text-white dark:border-white dark:bg-neutral-950 dark:text-neutral-950 data-checked:bg-neutral-950 data-checked:text-white dark:data-checked:bg-white dark:data-checked:text-neutral-950 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-950 dark:focus-visible:outline-white"
>
<Checkbox.Indicator className="flex data-unchecked:hidden">
<CheckIcon />
</Checkbox.Indicator>
</Checkbox.Root>
Gala
</label>
<label className="flex items-center gap-2 text-sm font-normal text-neutral-950 dark:text-white">
<Checkbox.Root
name="apple"
value="granny-smith-apple"
className="flex size-4 shrink-0 items-center justify-center border rounded-none p-0 border-neutral-950 bg-white text-white dark:border-white dark:bg-neutral-950 dark:text-neutral-950 data-checked:bg-neutral-950 data-checked:text-white dark:data-checked:bg-white dark:data-checked:text-neutral-950 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-950 dark:focus-visible:outline-white"
>
<Checkbox.Indicator className="flex data-unchecked:hidden">
<CheckIcon />
</Checkbox.Indicator>
</Checkbox.Root>
Granny Smith
</label>
</CheckboxGroup>
);
}
function CheckIcon(props: React.ComponentProps<'svg'>) {
return (
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
stroke="currentColor"
{...props}
style={{ display: 'block', ...props.style }}
>
<path d="m2.5 8.5 4 4 7-9" />
</svg>
);
}
CSS Modules
이 예시는 CSS Modules로 컴포넌트를 구현하는 방법을 보여줘요.
/* index.module.css */
.CheckboxGroup {
display: flex;
flex-direction: column;
align-items: start;
gap: 0.25rem;
color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
color: white;
}
}
.Caption {
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 700;
}
.Item {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 400;
}
.Checkbox {
box-sizing: border-box;
display: flex;
flex-shrink: 0;
width: 1rem;
height: 1rem;
align-items: center;
justify-content: center;
border: 1px solid oklch(14.5% 0 0deg);
border-radius: 0;
background-color: white;
color: white;
padding: 0;
margin: 0;
@media (prefers-color-scheme: dark) {
border: 1px solid white;
background-color: oklch(14.5% 0 0deg);
color: oklch(14.5% 0 0deg);
}
&[data-checked],
&[data-indeterminate] {
background-color: oklch(14.5% 0 0deg);
color: white;
@media (prefers-color-scheme: dark) {
background-color: white;
color: oklch(14.5% 0 0deg);
}
}
&:focus-visible {
outline: 2px solid oklch(14.5% 0 0deg);
outline-offset: 2px;
@media (prefers-color-scheme: dark) {
outline-color: white;
}
}
}
.Indicator {
display: flex;
&[data-unchecked] {
display: none;
}
}
/* index.tsx */
'use client';
import * as React from 'react';
import { Checkbox } from '@base-ui/react/checkbox';
import { CheckboxGroup } from '@base-ui/react/checkbox-group';
import styles from './index.module.css';
export default function ExampleCheckboxGroup() {
const id = React.useId();
return (
<CheckboxGroup
aria-labelledby={id}
defaultValue={['fuji-apple']}
className={styles.CheckboxGroup}
>
<div className={styles.Caption} id={id}>
Apples
</div>
<label className={styles.Item}>
<Checkbox.Root name="apple" value="fuji-apple" className={styles.Checkbox}>
<Checkbox.Indicator className={styles.Indicator}>
<CheckIcon />
</Checkbox.Indicator>
</Checkbox.Root>
Fuji
</label>
<label className={styles.Item}>
<Checkbox.Root name="apple" value="gala-apple" className={styles.Checkbox}>
<Checkbox.Indicator className={styles.Indicator}>
<CheckIcon />
</Checkbox.Indicator>
</Checkbox.Root>
Gala
</label>
<label className={styles.Item}>
<Checkbox.Root name="apple" value="granny-smith-apple" className={styles.Checkbox}>
<Checkbox.Indicator className={styles.Indicator}>
<CheckIcon />
</Checkbox.Indicator>
</Checkbox.Root>
Granny Smith
</label>
</CheckboxGroup>
);
}
function CheckIcon(props: React.ComponentProps<'svg'>) {
return (
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
stroke="currentColor"
{...props}
style={{ display: 'block', ...props.style }}
>
<path d="m2.5 8.5 4 4 7-9" />
</svg>
);
}
사용 가이드라인 (Usage guidelines)
- 폼 컨트롤에는 접근 가능한 이름(accessible name)이 있어야 해요:
<label>요소나Field,Fieldset컴포넌트로 만들 수 있어요. 체크박스 그룹에 라벨 지정하기와 폼 가이드를 참고하세요.
구조 (Anatomy)
Checkbox Group은 Checkbox와 함께 구성돼요. 컴포넌트를 임포트하고 함께 배치하세요.
import { Checkbox } from '@base-ui/react/checkbox';
import { CheckboxGroup } from '@base-ui/react/checkbox-group';
<CheckboxGroup>
<Checkbox.Root />
</CheckboxGroup>;
예시 (Examples)
체크박스 그룹에 라벨 지정하기
aria-labelledby와 형제 label 요소로 그룹에 라벨을 지정해요.
<div id="protocols-label">Allowed network protocols</div>
<CheckboxGroup aria-labelledby="protocols-label">{/* ... */}</CheckboxGroup>
각 체크박스에는 감싸는 <label>이 가장 간단한 라벨링 패턴이에요.
// @highlight
<label>
<Checkbox.Root value="http" />
HTTP
{/* @highlight */}
</label>
네이티브 버튼으로 렌더링하기
기본적으로 <Checkbox.Root>는 감싸는 label을 지원하기 위해 <span> 요소를 렌더링해요. 형제 label(htmlFor/id)을 사용할 때는 각 체크박스를 네이티브 버튼으로 렌더링하는 편이 좋아요.
<div id="protocols-label">Allowed network protocols</div>
<CheckboxGroup aria-labelledby="protocols-label">
<div>
<label htmlFor="protocol-http">HTTP</label>
{/* @highlight-text "nativeButton" "render={<button />}" */}
<Checkbox.Root id="protocol-http" value="http" nativeButton render={<button />}>
<Checkbox.Indicator />
</Checkbox.Root>
</div>
</CheckboxGroup>
네이티브 버튼을 감싸는 label과 함께 쓰려면 render 콜백을 사용해 잘못된 HTML을 피하고, 숨겨진 input을 label 밖에 배치할 수 있어요.
<div id="protocols-label">Allowed network protocols</div>
<CheckboxGroup aria-labelledby="protocols-label">
<Checkbox.Root
value="http"
nativeButton
// @highlight-start
render={(buttonProps) => (
<label>
<button {...buttonProps} />
HTTP
</label>
)}
{/* @highlight-end */}
/>
</CheckboxGroup>
폼 통합
그룹 라벨링과 폼 통합에는 Field와 Fieldset을 사용하세요.
<Form>
{/* @highlight */}
<Field.Root name="allowedNetworkProtocols">
<Fieldset.Root render={<CheckboxGroup />}>
<Fieldset.Legend>Allowed network protocols</Fieldset.Legend>
<Field.Item>
<Field.Label>
<Checkbox.Root value="http" />
HTTP
</Field.Label>
</Field.Item>
<Field.Item>
<Field.Label>
<Checkbox.Root value="https" />
HTTPS
</Field.Label>
</Field.Item>
<Field.Item>
<Field.Label>
<Checkbox.Root value="ssh" />
SSH
</Field.Label>
</Field.Item>
</Fieldset.Root>
</Field.Root>
</Form>
부모 체크박스 (Parent checkbox)
<CheckboxGroup> 안의 다른 체크박스들을 제어하는 체크박스를 만들 수 있어요.
<CheckboxGroup>을 제어 컴포넌트(controlled component)로 만드세요- 모든 자식 체크박스 값의 배열을
<CheckboxGroup>컴포넌트의allValuesprop에 전달하세요 - 부모
<Checkbox.Root>에parent불리언 prop을 추가하세요
자식 체크박스 중 일부만 체크됐을 때 그룹은 부모 체크박스의 indeterminate 상태를 제어해요.
데모 (Demo)
CSS Modules
이 예시는 CSS Modules로 컴포넌트를 구현하는 방법을 보여줘요.
/* index.module.css */
.CheckboxGroup {
display: flex;
flex-direction: column;
align-items: start;
gap: 0.25rem;
color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
color: white;
}
}
.Caption {
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 700;
}
.Item {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 400;
}
.Checkbox {
box-sizing: border-box;
display: flex;
flex-shrink: 0;
width: 1rem;
height: 1rem;
align-items: center;
justify-content: center;
border: 1px solid oklch(14.5% 0 0deg);
border-radius: 0;
background-color: white;
color: white;
padding: 0;
margin: 0;
@media (prefers-color-scheme: dark) {
border: 1px solid white;
background-color: oklch(14.5% 0 0deg);
color: oklch(14.5% 0 0deg);
}
&[data-checked],
&[data-indeterminate] {
background-color: oklch(14.5% 0 0deg);
color: white;
@media (prefers-color-scheme: dark) {
background-color: white;
color: oklch(14.5% 0 0deg);
}
}
&:focus-visible {
outline: 2px solid oklch(14.5% 0 0deg);
outline-offset: 2px;
@media (prefers-color-scheme: dark) {
outline-color: white;
}
}
}
.Indicator {
display: flex;
&[data-unchecked] {
display: none;
}
}
/* index.tsx */
'use client';
import * as React from 'react';
import { Checkbox } from '@base-ui/react/checkbox';
import { CheckboxGroup } from '@base-ui/react/checkbox-group';
import styles from './index.module.css';
const fruits = ['fuji-apple', 'gala-apple', 'granny-smith-apple'];
export default function ExampleCheckboxGroup() {
const id = React.useId();
const [value, setValue] = React.useState<string[]>([]);
return (
<CheckboxGroup
aria-labelledby={id}
value={value}
onValueChange={setValue}
allValues={fruits}
className={styles.CheckboxGroup}
style={{ marginLeft: '1rem' }}
>
<label className={styles.Item} id={id} style={{ marginLeft: '-1rem' }}>
<Checkbox.Root className={styles.Checkbox} parent>
<Checkbox.Indicator
className={styles.Indicator}
render={(props, state) => (
<span {...props}>{state.indeterminate ? <HorizontalRuleIcon /> : <CheckIcon />}</span>
)}
/>
</Checkbox.Root>
Apples
</label>
<label className={styles.Item}>
<Checkbox.Root value="fuji-apple" className={styles.Checkbox}>
<Checkbox.Indicator className={styles.Indicator}>
<CheckIcon />
</Checkbox.Indicator>
</Checkbox.Root>
Fuji
</label>
<label className={styles.Item}>
<Checkbox.Root value="gala-apple" className={styles.Checkbox}>
<Checkbox.Indicator className={styles.Indicator}>
<CheckIcon />
</Checkbox.Indicator>
</Checkbox.Root>
Gala
</label>
<label className={styles.Item}>
<Checkbox.Root value="granny-smith-apple" className={styles.Checkbox}>
<Checkbox.Indicator className={styles.Indicator}>
<CheckIcon />
</Checkbox.Indicator>
</Checkbox.Root>
Granny Smith
</label>
</CheckboxGroup>
);
}
function CheckIcon(props: React.ComponentProps<'svg'>) {
return (
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
stroke="currentColor"
{...props}
style={{ display: 'block', ...props.style }}
>
<path d="m2.5 8.5 4 4 7-9" />
</svg>
);
}
function HorizontalRuleIcon(props: React.ComponentProps<'svg'>) {
return (
<svg
width="12"
height="12"
viewBox="0 0 24 24"
fill="currentColor"
strokeWidth={1}
{...props}
style={{ display: 'block', ...props.style }}
>
<line
x1="3"
y1="12"
x2="21"
y2="12"
stroke="currentColor"
vectorEffect="non-scaling-stroke"
/>
</svg>
);
}
중첩 부모 체크박스
데모 (Demo)
CSS Modules
이 예시는 CSS Modules로 컴포넌트를 구현하는 방법을 보여줘요.
/* index.module.css */
.CheckboxGroup {
display: flex;
flex-direction: column;
align-items: start;
gap: 0.25rem;
color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
color: white;
}
}
.Caption {
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 700;
}
.Item {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 400;
}
.Checkbox {
box-sizing: border-box;
display: flex;
flex-shrink: 0;
width: 1rem;
height: 1rem;
align-items: center;
justify-content: center;
border: 1px solid oklch(14.5% 0 0deg);
border-radius: 0;
background-color: white;
color: white;
padding: 0;
margin: 0;
@media (prefers-color-scheme: dark) {
border: 1px solid white;
background-color: oklch(14.5% 0 0deg);
color: oklch(14.5% 0 0deg);
}
&[data-checked],
&[data-indeterminate] {
background-color: oklch(14.5% 0 0deg);
color: white;
@media (prefers-color-scheme: dark) {
background-color: white;
color: oklch(14.5% 0 0deg);
}
}
&:focus-visible {
outline: 2px solid oklch(14.5% 0 0deg);
outline-offset: 2px;
@media (prefers-color-scheme: dark) {
outline-color: white;
}
}
}
.Indicator {
display: flex;
&[data-unchecked] {
display: none;
}
}
/* index.tsx */
'use client';
import * as React from 'react';
import { Checkbox } from '@base-ui/react/checkbox';
import { CheckboxGroup } from '@base-ui/react/checkbox-group';
import styles from './index.module.css';
const mainPermissions = ['view-dashboard', 'manage-users', 'access-reports'];
const userManagementPermissions = ['create-user', 'edit-user', 'delete-user', 'assign-roles'];
export default function PermissionsForm() {
const id = React.useId();
const [mainValue, setMainValue] = React.useState<string[]>([]);
const [managementValue, setManagementValue] = React.useState<string[]>([]);
return (
<CheckboxGroup
aria-labelledby={id}
value={mainValue}
onValueChange={(value) => {
if (value.includes('manage-users')) {
setManagementValue(userManagementPermissions);
} else if (managementValue.length === userManagementPermissions.length) {
setManagementValue([]);
}
setMainValue(value);
}}
allValues={mainPermissions}
className={styles.CheckboxGroup}
style={{ marginLeft: '1rem' }}
>
<label className={styles.Item} id={id} style={{ marginLeft: '-1rem' }}>
<Checkbox.Root
className={styles.Checkbox}
parent
indeterminate={
managementValue.length > 0 &&
managementValue.length !== userManagementPermissions.length
}
>
<Checkbox.Indicator
className={styles.Indicator}
render={(props, state) => (
<span {...props}>{state.indeterminate ? <HorizontalRuleIcon /> : <CheckIcon />}</span>
)}
/>
</Checkbox.Root>
User Permissions
</label>
<label className={styles.Item}>
<Checkbox.Root value="view-dashboard" className={styles.Checkbox}>
<Checkbox.Indicator className={styles.Indicator}>
<CheckIcon />
</Checkbox.Indicator>
</Checkbox.Root>
View Dashboard
</label>
<label className={styles.Item}>
<Checkbox.Root value="access-reports" className={styles.Checkbox}>
<Checkbox.Indicator className={styles.Indicator}>
<CheckIcon />
</Checkbox.Indicator>
</Checkbox.Root>
Access Reports
</label>
<CheckboxGroup
aria-labelledby="manage-users-caption"
className={styles.CheckboxGroup}
value={managementValue}
onValueChange={(value) => {
if (value.length === userManagementPermissions.length) {
setMainValue((prev) => Array.from(new Set([...prev, 'manage-users'])));
} else {
setMainValue((prev) => prev.filter((v) => v !== 'manage-users'));
}
setManagementValue(value);
}}
allValues={userManagementPermissions}
style={{ marginLeft: '1rem' }}
>
<label className={styles.Item} id="manage-users-caption" style={{ marginLeft: '-1rem' }}>
<Checkbox.Root className={styles.Checkbox} parent>
<Checkbox.Indicator
className={styles.Indicator}
render={(props, state) => (
<span {...props}>
{state.indeterminate ? <HorizontalRuleIcon /> : <CheckIcon />}
</span>
)}
/>
</Checkbox.Root>
Manage Users
</label>
<label className={styles.Item}>
<Checkbox.Root value="create-user" className={styles.Checkbox}>
<Checkbox.Indicator className={styles.Indicator}>
<CheckIcon />
</Checkbox.Indicator>
</Checkbox.Root>
Create User
</label>
<label className={styles.Item}>
<Checkbox.Root value="edit-user" className={styles.Checkbox}>
<Checkbox.Indicator className={styles.Indicator}>
<CheckIcon />
</Checkbox.Indicator>
</Checkbox.Root>
Edit User
</label>
<label className={styles.Item}>
<Checkbox.Root value="delete-user" className={styles.Checkbox}>
<Checkbox.Indicator className={styles.Indicator}>
<CheckIcon />
</Checkbox.Indicator>
</Checkbox.Root>
Delete User
</label>
<label className={styles.Item}>
<Checkbox.Root value="assign-roles" className={styles.Checkbox}>
<Checkbox.Indicator className={styles.Indicator}>
<CheckIcon />
</Checkbox.Indicator>
</Checkbox.Root>
Assign Roles
</label>
</CheckboxGroup>
</CheckboxGroup>
);
}
function CheckIcon(props: React.ComponentProps<'svg'>) {
return (
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
stroke="currentColor"
{...props}
style={{ display: 'block', ...props.style }}
>
<path d="m2.5 8.5 4 4 7-9" />
</svg>
);
}
function HorizontalRuleIcon(props: React.ComponentProps<'svg'>) {
return (
<svg
width="12"
height="12"
viewBox="0 0 24 24"
fill="currentColor"
strokeWidth={1}
{...props}
style={{ display: 'block', ...props.style }}
>
<line
x1="3"
y1="12"
x2="21"
y2="12"
stroke="currentColor"
vectorEffect="non-scaling-stroke"
/>
</svg>
);
}
API 레퍼런스 (API reference)
CheckboxGroup
일련의 체크박스에 공유 상태를 제공해요.
CheckboxGroup Props:
| Prop | Type | Default | Description |
|---|---|---|---|
| defaultValue | string[] |
- | 그룹에서 초기에 체크되어야 하는 체크박스의 이름이에요. 제어(controlled) 체크박스 그룹을 렌더링하려면 value prop을 대신 사용하세요. |
| value | string[] |
- | 그룹에서 체크되어야 하는 체크박스의 이름이에요. 비제어(uncontrolled) 체크박스 그룹을 렌더링하려면 defaultValue prop을 대신 사용하세요. |
| onValueChange | ((value: string[], eventDetails: CheckboxGroup.ChangeEventDetails) => void) |
- | 그룹의 체크박스가 체크되거나 해제될 때 호출되는 이벤트 핸들러예요. 새 값을 인자로 제공해요. |
| allValues | string[] |
- | 그룹 안의 모든 체크박스의 이름이에요. 부모 체크박스를 만들 때 사용하세요. |
| disabled | boolean |
false |
컴포넌트가 사용자 상호작용을 무시할지 여부예요. |
| className | string | ((state: CheckboxGroup.State) => string | undefined) |
- | 요소에 적용되는 CSS 클래스, 또는 컴포넌트 상태를 기반으로 클래스를 반환하는 함수예요. |
| style | React.CSSProperties | ((state: CheckboxGroup.State) => React.CSSProperties | undefined) |
- | 요소에 적용되는 스타일, 또는 컴포넌트 상태를 기반으로 스타일 객체를 반환하는 함수예요. |
| render | ReactElement | ((props: HTMLProps, state: CheckboxGroup.State) => ReactElement) |
- | 컴포넌트의 HTML 요소를 다른 태그로 대체하거나 다른 컴포넌트와 합성할 수 있게 해줘요. ReactElement 또는 렌더링할 요소를 반환하는 함수를 받아요. |
CheckboxGroup Data Attributes:
| Attribute | Type | Description |
|---|---|---|
| data-disabled | - | 체크박스 그룹이 비활성화됐을 때 존재해요. |
CheckboxGroup.Props
CheckboxGroup props의 재내보내기(re-export)예요.
CheckboxGroup.State
type CheckboxGroupState = {
/** Whether the component should ignore user interaction. */
disabled: boolean;
/** Whether the field has been touched. */
touched: boolean;
/** Whether the field value has changed from its initial value. */
dirty: boolean;
/** Whether the field is valid. */
valid: boolean | null;
/** Whether the field has a value. */
filled: boolean;
/** Whether the field is focused. */
focused: boolean;
};
CheckboxGroup.ChangeEventReason
type CheckboxGroupChangeEventReason = 'none';
CheckboxGroup.ChangeEventDetails
type CheckboxGroupChangeEventDetails = {
/** The reason for the event. */
reason: 'none';
/** The native event associated with the custom event. */
event: Event;
/** Cancels Base UI from handling the event. */
cancel: () => void;
/** Allows the event to propagate in cases where Base UI will stop the propagation. */
allowPropagation: () => void;
/** Indicates whether the event has been canceled. */
isCanceled: boolean;
/** Indicates whether the event is allowed to propagate. */
isPropagationAllowed: boolean;
/** The element that triggered the event, if applicable. */
trigger: Element | undefined;
};
Canonical Types
Canonical: Alias 매핑 — Canonical의 네임스페이스가 이미 임포트되어 있으면 Canonical을, 아니면 Alias를 사용하세요.
CheckboxGroup.State:CheckboxGroupStateCheckboxGroup.Props:CheckboxGroupPropsCheckboxGroup.ChangeEventReason:CheckboxGroupChangeEventReasonCheckboxGroup.ChangeEventDetails:CheckboxGroupChangeEventDetails