0
# RC Switch
1
2
RC Switch is a lightweight, accessible React toggle switch component with extensive customization options. It provides a complete switch implementation with controlled/uncontrolled state management, keyboard navigation, loading states, and comprehensive styling control.
3
4
## Package Information
5
6
- **Package Name**: rc-switch
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install rc-switch`
10
11
## Core Imports
12
13
```typescript
14
import Switch from "rc-switch";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const Switch = require("rc-switch");
21
```
22
23
## Basic Usage
24
25
```typescript
26
import React, { useState } from "react";
27
import Switch from "rc-switch";
28
import "rc-switch/assets/index.css"; // Import default styles
29
30
export default function App() {
31
const [checked, setChecked] = useState(false);
32
33
return (
34
<Switch
35
checked={checked}
36
onChange={(value) => setChecked(value)}
37
checkedChildren="ON"
38
unCheckedChildren="OFF"
39
/>
40
);
41
}
42
```
43
44
## Architecture
45
46
RC Switch is built around a single `Switch` component that:
47
48
- **State Management**: Uses `rc-util`'s `useMergedState` hook for controlled/uncontrolled state handling
49
- **Accessibility**: Implements ARIA `switch` role with proper `aria-checked` attributes
50
- **Keyboard Support**: Built-in LEFT/RIGHT arrow key navigation using `rc-util`'s KeyCode constants
51
- **Forward Ref**: Provides direct access to the underlying HTMLButtonElement
52
- **Event System**: Separate onChange/onClick handlers with consistent event signatures
53
54
## Capabilities
55
56
### Switch Component
57
58
Main toggle switch component with full state management and accessibility features.
59
60
```typescript { .api }
61
/**
62
* React switch component with toggle functionality
63
* @param props - Switch configuration props
64
* @param ref - Forwarded ref to HTMLButtonElement
65
* @returns JSX element representing the switch
66
*/
67
declare const Switch: React.ForwardRefExoticComponent<
68
SwitchProps & React.RefAttributes<HTMLButtonElement>
69
>;
70
71
interface SwitchProps extends Omit<React.HTMLAttributes<HTMLButtonElement>, 'onChange' | 'onClick'> {
72
/** Additional CSS class name */
73
className?: string;
74
/** CSS class prefix for styling (default: 'rc-switch') */
75
prefixCls?: string;
76
/** Whether the switch is disabled */
77
disabled?: boolean;
78
/** Content displayed when switch is checked */
79
checkedChildren?: React.ReactNode;
80
/** Content displayed when switch is unchecked */
81
unCheckedChildren?: React.ReactNode;
82
/** Callback fired when switch state changes */
83
onChange?: SwitchChangeEventHandler;
84
/** Keyboard event handler */
85
onKeyDown?: React.KeyboardEventHandler<HTMLButtonElement>;
86
/** Click event handler */
87
onClick?: SwitchClickEventHandler;
88
/** Tab index for keyboard navigation */
89
tabIndex?: number;
90
/** Whether component should auto focus when mounted */
91
autoFocus?: boolean;
92
/** Controlled checked state */
93
checked?: boolean;
94
/** Default checked state for uncontrolled usage */
95
defaultChecked?: boolean;
96
/** Loading indicator icon */
97
loadingIcon?: React.ReactNode;
98
/** Inline styles */
99
style?: React.CSSProperties;
100
/** Title attribute for accessibility */
101
title?: string;
102
}
103
```
104
105
**Usage Examples:**
106
107
```typescript
108
import React, { useState } from "react";
109
import Switch from "rc-switch";
110
111
// Uncontrolled switch
112
<Switch defaultChecked={true} onChange={(checked) => console.log(checked)} />
113
114
// Controlled switch
115
const [checked, setChecked] = useState(false);
116
<Switch checked={checked} onChange={setChecked} />
117
118
// With custom content
119
<Switch
120
checkedChildren="开"
121
unCheckedChildren="关"
122
onChange={(checked) => console.log(`Switch is ${checked ? 'on' : 'off'}`)}
123
/>
124
125
// Disabled state
126
<Switch disabled checked={true} />
127
128
// With loading indicator
129
<Switch loadingIcon={<SpinnerIcon />} />
130
131
// Custom styling
132
<Switch
133
className="my-switch"
134
prefixCls="custom-switch"
135
style={{ marginTop: 20 }}
136
/>
137
138
// Auto focus on mount
139
<Switch autoFocus onChange={(checked) => console.log(checked)} />
140
141
// Ref access for programmatic focus management
142
const switchRef = useRef<HTMLButtonElement>(null);
143
useEffect(() => {
144
switchRef.current?.focus();
145
}, []);
146
<Switch ref={switchRef} />
147
```
148
149
### Event Handlers
150
151
Type-safe event handler definitions for switch interactions.
152
153
```typescript { .api }
154
/**
155
* Event handler for switch state changes
156
* @param checked - New checked state
157
* @param event - Mouse or keyboard event that triggered the change
158
*/
159
type SwitchChangeEventHandler = (
160
checked: boolean,
161
event: React.MouseEvent<HTMLButtonElement> | React.KeyboardEvent<HTMLButtonElement>
162
) => void;
163
164
/**
165
* Event handler for switch clicks (legacy alias for SwitchChangeEventHandler)
166
* @param checked - Current checked state after click
167
* @param event - Mouse or keyboard event that triggered the click
168
*/
169
type SwitchClickEventHandler = SwitchChangeEventHandler;
170
```
171
172
### Display Name
173
174
```typescript { .api }
175
/** Component display name for debugging */
176
Switch.displayName = 'Switch';
177
```
178
179
## Keyboard Navigation
180
181
RC Switch includes built-in keyboard support:
182
183
- **LEFT Arrow**: Changes switch to unchecked state
184
- **RIGHT Arrow**: Changes switch to checked state
185
- **Space/Enter**: Toggles switch state (default button behavior)
186
187
## CSS Classes
188
189
RC Switch applies dynamic CSS classes for styling:
190
191
- `{prefixCls}` - Base class (default: 'rc-switch')
192
- `{prefixCls}-checked` - Applied when switch is checked
193
- `{prefixCls}-disabled` - Applied when switch is disabled
194
- `{prefixCls}-inner` - Inner container for switch content
195
- `{prefixCls}-inner-checked` - Container for checked children
196
- `{prefixCls}-inner-unchecked` - Container for unchecked children
197
198
## Browser Compatibility
199
200
- IE11, Edge
201
- Firefox (last 2 versions)
202
- Chrome (last 2 versions)
203
- Safari (last 2 versions)
204
- Electron (last 2 versions)