스위치
스위치 (Switch)
두 상태(켜짐/꺼짐) 사이를 전환할 때 사용하는 토글 스위치 컴포넌트입니다. 체크박스와 달리 토글 즉시 상태가 바로 바뀝니다.
출처: 문서
본문
언제 사용하나요 (When To Use)
- 두 상태 사이의 전환이나 켜짐/꺼짐 상태를 표현해야 할 때
Switch와Checkbox의 차이는,Switch는 토글하는 즉시 상태 변경이 일어나는 반면Checkbox는 일반적으로 상태 표시에 사용되며 제출(submit) 동작과 함께 사용해야 한다는 점입니다.
예제 (Examples)
기본 (Basic)
가장 기본적인 사용법입니다.
import React from 'react';
import { Switch } from 'antd';
const onChange = (checked: boolean) => {
console.log(`switch to ${checked}`);
};
const App: React.FC = () => <Switch defaultChecked onChange={onChange} />;
export default App;
비활성화 (Disabled)
Switch의 비활성화 상태입니다.
import React, { useState } from 'react';
import { Button, Space, Switch } from 'antd';
const App: React.FC = () => {
const [disabled, setDisabled] = useState(true);
const toggle = () => {
setDisabled(!disabled);
};
return (
<Space vertical>
<Switch disabled={disabled} defaultChecked />
<Button type="primary" onClick={toggle}>
Toggle disabled
</Button>
</Space>
);
};
export default App;
텍스트 & 아이콘 (Text & icon)
텍스트와 아이콘을 함께 표시합니다.
import React from 'react';
import { CheckOutlined, CloseOutlined, FrownOutlined, SmileOutlined } from '@ant-design/icons';
import { Flex, Switch } from 'antd';
const Demo: React.FC = () => (
<Flex gap="medium" align="flex-start" justify="flex-start" vertical>
<Switch checkedChildren="On" unCheckedChildren="Off" defaultChecked />
<Switch checkedChildren={1} unCheckedChildren={0} defaultChecked />
<Switch
defaultChecked
checkedChildren={<CheckOutlined />}
unCheckedChildren={<CloseOutlined />}
/>
<Switch
defaultChecked
checkedChildren={
<Flex gap={4} justify="flex-start" align="center">
<SmileOutlined />
Happy
</Flex>
}
unCheckedChildren={
<Flex gap={4} justify="flex-start" align="center">
<FrownOutlined />
Sad
</Flex>
}
/>
</Flex>
);
export default Demo;
두 가지 크기 (Two sizes)
size="small"은 작은 크기의 스위치를 나타냅니다.
import React from 'react';
import { Switch } from 'antd';
const App: React.FC = () => (
<>
<Switch defaultChecked />
<br />
<Switch size="small" defaultChecked />
</>
);
export default App;
로딩 (Loading)
스위치의 대기(pending) 상태를 표시합니다.
import React from 'react';
import { Switch } from 'antd';
const App: React.FC = () => (
<>
<Switch loading defaultChecked />
<br />
<Switch size="small" loading />
</>
);
export default App;
커스텀 시맨틱 DOM 스타일링 (Custom semantic dom styling)
classNames와 styles에 객체 또는 함수를 넘겨서 Switch의 시맨틱 DOM 스타일을 커스터마이즈할 수 있습니다.
import React from 'react';
import { Flex, Switch } from 'antd';
import type { GetProp, SwitchProps } from 'antd';
import { createStyles } from 'antd-style';
const useStyle = createStyles((props) => {
const { cssVar, prefixCls, css } = props;
return {
root: css`
width: 40px;
background-color: ${cssVar.colorPrimary};
`,
muiRoot: css`
min-width: 32px;
height: 14px;
line-height: 14px;
&&.${prefixCls}-switch-checked {
background-color: rgba(25, 118, 210, 0.5);
.${prefixCls}-switch-handle {
inset-inline-start: calc(100% - 17px);
}
}
`,
muiIndicator: css`
top: -3px;
width: 20px;
height: 20px;
&&& {
inset-inline-start: -3px;
}
&&&::before {
background-color: rgb(25, 118, 210);
border-radius: 999px;
box-shadow:
rgba(0, 0, 0, 0.2) 0 2px 1px -1px,
rgba(0, 0, 0, 0.14) 0 1px 1px 0,
rgba(0, 0, 0, 0.12) 0 1px 4px 0;
}
`,
};
});
const stylesObject: SwitchProps['styles'] = {
root: {
backgroundColor: '#F5D2D2',
},
};
const stylesFn: SwitchProps['styles'] = (info): GetProp<SwitchProps, 'styles', 'Return'> => {
if (info.props.size === 'medium') {
return {
root: {
backgroundColor: '#BDE3C3',
},
};
}
return {};
};
const Demo: React.FC = () => {
const { styles: classNames } = useStyle();
return (
<Flex vertical align="flex-start" justify="flex-start" gap="medium">
<Switch
size="small"
checkedChildren="on"
unCheckedChildren="off"
styles={stylesObject}
classNames={{ root: classNames.root }}
/>
<Switch
size="medium"
checkedChildren="on"
unCheckedChildren="off"
styles={stylesFn}
classNames={classNames}
/>
<Switch
defaultChecked
classNames={{ root: classNames.muiRoot, indicator: classNames.muiIndicator }}
/>
</Flex>
);
};
export default Demo;
API
Common props ref:Common props
| Property | Description | Type | Default | Version | Global Config |
|---|---|---|---|---|---|
| checked | Determine whether the Switch is checked | boolean | false | × | |
| checkedChildren | The content to be shown when the state is checked | ReactNode | - | × | |
| classNames | Customize class for each semantic structure inside the component. Supports object or function. | Record<SemanticDOM, string> | (info: { props })=> Record<SemanticDOM, string> | - | 6.0.0 | |
| defaultChecked | Whether to set the initial state | boolean | false | × | |
| defaultValue | Alias for defaultChecked |
boolean | - | 5.12.0 | × |
| disabled | Disable switch | boolean | false | × | |
| loading | Loading state of switch | boolean | false | × | |
| size | The size of the Switch, options: medium small |
'medium' | 'small' |
medium |
× | |
| styles | Customize inline style for each semantic structure inside the component. Supports object or function. | Record<SemanticDOM, CSSProperties> | (info: { props })=> Record<SemanticDOM, CSSProperties> | - | 6.0.0 | |
| unCheckedChildren | The content to be shown when the state is unchecked | ReactNode | - | × | |
| value | Alias for checked |
boolean | - | 5.12.0 | × |
| onChange | Trigger when the checked state is changing | function(checked: boolean, event: Event) | - | × | |
| onClick | Trigger when clicked | function(checked: boolean, event: Event) | - | × |
메서드 (Methods)
| Name | Description |
|---|---|
| blur() | Remove focus |
| focus() | Get focus |
시맨틱 DOM (Semantic DOM)
https://ant.design/components/switch/semantic.md
디자인 토큰 (Design Token)
컴포넌트 토큰 (Component Token - Switch)
| Token Name | Description | Type | Default Value |
|---|---|---|---|
| handleBg | Background color of Switch handle | string | #fff |
| handleShadow | Shadow of Switch handle | string | 0 2px 4px 0 rgba(0,35,11,0.2) |
| handleSize | Size of Switch handle | number | 18 |
| handleSizeSM | Size of small Switch handle | number | 12 |
| innerMaxMargin | Maximum margin of content area | number | 24 |
| innerMaxMarginSM | Maximum margin of content area of small Switch | number | 18 |
| innerMinMargin | Minimum margin of content area | number | 9 |
| innerMinMarginSM | Minimum margin of content area of small Switch | number | 6 |
| trackHeight | Height of Switch | string | number | 22 |
| trackHeightSM | Height of small Switch | string | number | 16 |
| trackMinWidth | Minimum width of Switch | string | number | 44 |
| trackMinWidthSM | Minimum width of small Switch | string | number | 28 |
| trackPadding | Padding of Switch | number | 2 |
글로벌 토큰 (Global Token)
| Token Name | Description | Type | Default Value |
|---|---|---|---|
| colorPrimary | Brand color is one of the most direct visual elements to reflect the characteristics and communication of the product. After you have selected the brand color, we will automatically generate a complete color palette and assign it effective design semantics. | string | |
| colorPrimaryBorder | The stroke color under the main color gradient, used on the stroke of components such as Slider. | string | |
| colorPrimaryHover | Hover state under the main color gradient. | string | |
| colorText | Default text color which comply with W3C standards, and this color is also the darkest neutral color. | string | |
| colorTextLightSolid | Control the highlight color of text with background color, such as the text in Primary Button components. | string | |
| colorTextQuaternary | The fourth level of text color is the lightest text color, such as form input prompt text, disabled color text, etc. | string | |
| colorTextTertiary | The third level of text color is generally used for descriptive text, such as form supplementary explanation text, list descriptive text, etc. | string | |
| fontFamily | The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. | string | |
| fontSize | The most widely used font size in the design system, from which the text gradient will be derived. | number | |
| fontSizeIcon | Control the font size of operation icon in Select, Cascader, etc. Normally same as fontSizeSM. | number | |
| fontSizeSM | Small font size | number | |
| lineHeight | Line height of text. | number | |
| lineWidthFocus | Control the width of the line when the component is in focus state. | number | |
| marginXXS | Control the margin of an element, with the smallest size. | number | |
| motionDurationMid | Motion speed, medium speed. Used for medium element animation interaction. | string | |
| opacityLoading | Control the opacity of the loading state. | number |
FAQ
Form.Item에서 왜 동작하지 않나요? {#faq-binding-data}
Form.Item은 기본적으로 value 속성에 값을 바인딩하지만, Switch의 값 속성은 checked입니다. valuePropName을 사용해 바인딩 속성을 변경할 수 있습니다.
<Form.Item name="fieldA" valuePropName="checked">
<Switch />
</Form.Item>