Checkbox
Checkbox (체크박스)
Checkbox는 여러 옵션 중 여러 값을 선택할 때 사용하는 컴포넌트예요.
출처: 문서
본문
언제 사용하나요
- 여러 옵션에서 여러 값을 선택할 때.
- 체크박스를 하나만 사용하면 Switch를 사용해 두 상태를 전환하는 것과 같아요. 차이는 Switch는 상태 변경을 바로 트리거하지만, Checkbox는 상태가 바뀌었다고 표시만 하고 제출(submit)이 필요하다는 점이에요.
예제 (Examples)
기본 (Basic)
체크박스의 기본 사용법이에요.
import React from 'react';
import { Checkbox } from 'antd';
import type { CheckboxProps } from 'antd';
const onChange: CheckboxProps['onChange'] = (e) => {
console.log(`checked = ${e.target.checked}`);
};
const App: React.FC = () => <Checkbox onChange={onChange}>Checkbox</Checkbox>;
export default App;
비활성 (Disabled)
비활성화된 체크박스예요.
import React from 'react';
import { Checkbox, Flex } from 'antd';
const App: React.FC = () => (
<Flex vertical gap="medium">
<Checkbox defaultChecked={false} disabled />
<Checkbox indeterminate disabled />
<Checkbox defaultChecked disabled />
</Flex>
);
export default App;
제어된 체크박스 (Controlled Checkbox)
다른 컴포넌트와 통신해요.
import React, { useState } from 'react';
import { Button, Checkbox } from 'antd';
import type { CheckboxProps } from 'antd';
const App: React.FC = () => {
const [checked, setChecked] = useState(true);
const [disabled, setDisabled] = useState(false);
const toggleChecked = () => {
setChecked(!checked);
};
const toggleDisable = () => {
setDisabled(!disabled);
};
const onChange: CheckboxProps['onChange'] = (e) => {
console.log('checked = ', e.target.checked);
setChecked(e.target.checked);
};
const label = `${checked ? 'Checked' : 'Unchecked'}-${disabled ? 'Disabled' : 'Enabled'}`;
return (
<>
<p style={{ marginBottom: '20px' }}>
<Checkbox checked={checked} disabled={disabled} onChange={onChange}>
{label}
</Checkbox>
</p>
<p>
<Button type="primary" size="small" onClick={toggleChecked}>
{!checked ? 'Check' : 'Uncheck'}
</Button>
<Button style={{ margin: '0 10px' }} type="primary" size="small" onClick={toggleDisable}>
{!disabled ? 'Disable' : 'Enable'}
</Button>
</p>
</>
);
};
export default App;
체크박스 그룹 (Checkbox Group)
배열로 체크박스 그룹을 생성해요.
import React from 'react';
import { Checkbox } from 'antd';
import type { CheckboxOptionType, GetProp } from 'antd';
const onChange: GetProp<typeof Checkbox.Group, 'onChange'> = (checkedValues) => {
console.log('checked = ', checkedValues);
};
const plainOptions = ['Apple', 'Pear', 'Orange'];
const options: CheckboxOptionType<string>[] = [
{ label: 'Apple', value: 'Apple', className: 'label-1' },
{ label: 'Pear', value: 'Pear', className: 'label-2' },
{ label: 'Orange', value: 'Orange', className: 'label-3' },
];
const optionsWithDisabled: CheckboxOptionType<string>[] = [
{ label: 'Apple', value: 'Apple', className: 'label-1' },
{ label: 'Pear', value: 'Pear', className: 'label-2' },
{ label: 'Orange', value: 'Orange', className: 'label-3', disabled: false },
];
const App: React.FC = () => (
<>
<Checkbox.Group options={plainOptions} defaultValue={['Apple']} onChange={onChange} />
<br />
<br />
<Checkbox.Group options={options} defaultValue={['Pear']} onChange={onChange} />
<br />
<br />
<Checkbox.Group
options={optionsWithDisabled}
disabled
defaultValue={['Apple']}
onChange={onChange}
/>
</>
);
export default App;
전체 선택 (Check all)
indeterminate 속성으로 '전체 선택' 효과를 만들 수 있어요.
import React, { useState } from 'react';
import { Checkbox, Divider } from 'antd';
import type { CheckboxProps } from 'antd';
const CheckboxGroup = Checkbox.Group;
const plainOptions = ['Apple', 'Pear', 'Orange'];
const defaultCheckedList = ['Apple', 'Orange'];
const App: React.FC = () => {
const [checkedList, setCheckedList] = useState<string[]>(defaultCheckedList);
const checkAll = plainOptions.length === checkedList.length;
const indeterminate = checkedList.length > 0 && checkedList.length < plainOptions.length;
const onChange = (list: string[]) => {
setCheckedList(list);
};
const onCheckAllChange: CheckboxProps['onChange'] = (e) => {
setCheckedList(e.target.checked ? plainOptions : []);
};
return (
<>
<Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>
Check all
</Checkbox>
<Divider />
<CheckboxGroup options={plainOptions} value={checkedList} onChange={onChange} />
</>
);
};
export default App;
Grid와 함께 사용 (Use with Grid)
Checkbox.Group에서 Checkbox와 Grid를 함께 사용해 복잡한 레이아웃을 구현할 수 있어요.
import React from 'react';
import { Checkbox, Col, Row } from 'antd';
import type { GetProp } from 'antd';
const onChange: GetProp<typeof Checkbox.Group, 'onChange'> = (checkedValues) => {
console.log('checked = ', checkedValues);
};
const App: React.FC = () => (
<Checkbox.Group style={{ width: '100%' }} onChange={onChange}>
<Row>
<Col span={8}>
<Checkbox value="A">A</Checkbox>
</Col>
<Col span={8}>
<Checkbox value="B">B</Checkbox>
</Col>
<Col span={8}>
<Checkbox value="C">C</Checkbox>
</Col>
<Col span={8}>
<Checkbox value="D">D</Checkbox>
</Col>
<Col span={8}>
<Checkbox value="E">E</Checkbox>
</Col>
</Row>
</Checkbox.Group>
);
export default App;
커스텀 시맨틱 DOM 스타일링
classNames와 styles에 객체/함수를 전달해 Checkbox의 시맨틱 DOM 스타일을 커스터마이즈할 수 있어요.
import React from 'react';
import { Checkbox, Flex } from 'antd';
import type { CheckboxProps, GetProp } from 'antd';
import { createStyles } from 'antd-style';
import { clsx } from 'clsx';
const useStyles = createStyles(({ token, css }) => ({
root: css`
border-radius: ${token.borderRadius}px;
background-color: ${token.colorBgContainer};
`,
icon: css`
border-color: ${token.colorWarning};
`,
label: css`
color: ${token.colorTextDisabled};
font-weight: bold;
`,
iconChecked: css`
background-color: ${token.colorWarning};
`,
labelChecked: css`
color: ${token.colorWarning};
`,
}));
// Object style
const styles: CheckboxProps['styles'] = {
icon: {
borderRadius: 6,
},
label: {
color: 'blue',
},
};
const App: React.FC = () => {
const { styles: classNamesStyles } = useStyles();
// Function classNames - dynamically adjust based on checked state
const classNamesFn: CheckboxProps['classNames'] = (
info,
): GetProp<CheckboxProps, 'classNames', 'Return'> => {
if (info.props.checked) {
return {
root: clsx(classNamesStyles.root),
icon: clsx(classNamesStyles.icon, classNamesStyles.iconChecked),
label: clsx(classNamesStyles.label, classNamesStyles.labelChecked),
};
}
return {
root: classNamesStyles.root,
icon: classNamesStyles.icon,
label: classNamesStyles.label,
};
};
return (
<Flex vertical gap="medium">
<Checkbox styles={styles}>Object styles</Checkbox>
<Checkbox classNames={classNamesFn} defaultChecked>
Function styles
</Checkbox>
</Flex>
);
};
export default App;
API
공통 props 참고: Common props
Checkbox
| 속성 | 설명 | 타입 | 기본값 | 버전 | 전역 설정 |
|---|---|---|---|---|---|
| checked | 체크박스 선택 여부 지정 | boolean | false | × | |
| classNames | 컴포넌트 내부 각 시맨틱 구조의 클래스 커스터마이즈. 객체 또는 함수 지원 | Record<SemanticDOM, string> | (info: { props })=> Record<SemanticDOM, string> | - | 6.0.0 | |
| defaultChecked | 초기 상태 지정: 체크박스 선택 여부 | boolean | false | × | |
| disabled | 체크박스 비활성화 | boolean | false | × | |
| indeterminate | 체크박스의 미결정(indeterminate) 체크 상태 | boolean | false | × | |
| onChange | 상태가 바뀔 때 트리거되는 콜백 함수 | (e: CheckboxChangeEvent) => void | - | × | |
| onBlur | 컴포넌트를 벗어날 때 호출 | function() | - | × | |
| onFocus | 컴포넌트에 들어올 때 호출 | function() | - | × | |
| styles | 컴포넌트 내부 각 시맨틱 구조의 인라인 스타일 커스터마이즈. 객체 또는 함수 지원 | Record<SemanticDOM, CSSProperties> | (info: { props })=> Record<SemanticDOM, CSSProperties> | - | 6.0.0 |
Checkbox.Group
| 속성 | 설명 | 타입 | 기본값 | 버전 |
|---|---|---|---|---|
| defaultValue | 기본 선택값 | (string | number)[] | [] | |
| disabled | 모든 체크박스 비활성화 | boolean | false | |
| name | 모든 input[type="checkbox"] 자식의 name 속성 |
string | - | |
| options | 옵션 지정 | string[] | number[] | Option[] | [] | |
| value | 현재 선택값 설정에 사용 | (string | number | boolean)[] | [] | |
| title | 옵션의 title | string |
- | |
| className | 옵션의 className | string |
- | 5.25.0 |
| style | 옵션의 스타일 | React.CSSProperties |
- | |
| onChange | 상태가 바뀔 때 트리거되는 콜백 함수 | (checkedValue: T[]) => void | - |
Option
interface Option {
label: string;
value: string;
disabled?: boolean;
}
메서드 (Methods)
Checkbox
| 이름 | 설명 | 버전 |
|---|---|---|
| blur() | 포커스 제거 | |
| focus() | 포커스 얻기 | |
| nativeElement | Checkbox의 DOM 노드 반환 | 5.17.3 |
시맨틱 DOM (Semantic DOM)
https://ant.design/components/checkbox/semantic.md
디자인 토큰 (Design Token)
전역 토큰 (Global Token)
| 토큰 이름 | 설명 | 타입 | 기본값 |
|---|---|---|---|
| borderRadiusSM | SM 크기 테두리 반지름, Button, Input, Select 등 작은 크기 입력 컴포넌트에 사용 | number | |
| colorBgContainer | 컨테이너 배경색. 예: 기본 버튼, 입력박스 등. colorBgElevated와 혼동하지 말 것. |
string | |
| colorBgContainerDisabled | 비활성 상태 컨테이너의 배경색 제어. | string | |
| colorBorder | 기본 테두리색, 요소를 구분하는 데 사용. 예: 폼 구분선, 카드 구분선 등 | string | |
| colorPrimary | 브랜드 색. 제품의 특성과 커뮤니케이션을 반영하는 가장 직접적인 시각 요소. 선택하면 완전한 색 팔레트가 자동 생성 | string | |
| colorPrimaryBorder | 기본 색 그라데이션 아래의 스트로크 색. Slider 같은 컴포넌트의 스트로크에 사용 | string | |
| colorPrimaryHover | 기본 색 그라데이션 아래의 호버 상태. | string | |
| colorText | W3C 표준을 준수하는 기본 텍스트 색. 가장 어두운 중성색이기도 함. | string | |
| colorTextDisabled | 비활성 상태 텍스트의 색 제어. | string | |
| colorWhite | 테마에 의해 바뀌지 않는 순수 흰색 | string | |
| controlInteractiveSize | 컨트롤 컴포넌트의 인터랙티브 크기 제어. | number | |
| fontFamily | 시스템 기본 인터페이스 폰트와 화면 표시에 적합한 대체 폰트 라이브러리 세트 제공 | string | |
| fontSize | 디자인 시스템에서 가장 널리 사용되는 폰트 크기. | number | |
| fontSizeLG | 큰 폰트 크기 | number | |
| lineHeight | 텍스트의 줄 높이. | number | |
| lineType | 기본 컴포넌트의 테두리 스타일 | string | |
| lineWidth | 기본 컴포넌트의 테두리 너비 | number | |
| lineWidthBold | Button, Input, Select 등 아웃라인 계열 컴포넌트의 기본 선 너비 | number | |
| lineWidthFocus | 컴포넌트가 포커스 상태일 때 선 너비 제어. | number | |
| marginXS | 요소의 여백 제어, 작은 크기. | number | |
| motionDurationFast | 모션 속도, 빠른 속도. 작은 요소 애니메이션 상호작용에 사용. | string | |
| motionDurationMid | 모션 속도, 중간 속도. 중간 요소 애니메이션 상호작용에 사용. | string | |
| motionDurationSlow | 모션 속도, 느린 속도. 대형 요소 애니메이션 상호작용에 사용. | string | |
| motionEaseInBack | 프리셋 모션 곡선. | string | |
| motionEaseOutBack | 프리셋 모션 곡선. | string | |
| paddingXS | 요소의 매우 작은 패딩 제어. | number |
FAQ
Form.Item에서 동작하지 않는 이유는? {#faq-form-item-limitations}
Form.Item은 기본적으로 value 속성에 값을 바인딩하지만, Checkbox의 값 속성은 checked예요. valuePropName으로 바인딩 속성을 변경할 수 있어요.
<Form.Item name="fieldA" valuePropName="checked">
<Checkbox />
</Form.Item>
더 알아보기 (Learn more)
- Radio 컴포넌트 — 단일 선택
- Switch 컴포넌트 — 두 상태 전환
- Form 컴포넌트 — 폼에서 활용
- Ant Design 시작하기 — 프로젝트 설정