-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathToggleSwitch.tsx
More file actions
88 lines (76 loc) · 2.38 KB
/
ToggleSwitch.tsx
File metadata and controls
88 lines (76 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import * as React from 'react';
import styles from './ToggleSwitch.scss';
/**
* Slider positions for `ToggleSwitch`.
*/
export const enum ToggleSwitchPosition {
Left = 'left',
Right = 'right'
}
/**
* Event arguments for `IToggleSwitchProps.onToggle`.
*/
export interface IToggleEventArgs {
sliderPosition: ToggleSwitchPosition;
}
export interface IToggleSwitchProps {
/**
* The CSS color when the `ToggleSwitch` slider is in the left position.
* Example value: `"#800000"`
*/
leftColor: string;
/**
* The CSS color when the `ToggleSwitch` slider is in the right position.
* Example value: `"#008000"`
*/
rightColor: string;
/**
* An event that fires when the `ToggleSwitch` control is clicked.
*/
onToggle?: (sender: ToggleSwitch, args: IToggleEventArgs) => void;
}
/**
* Private state for ToggleSwitch.
*/
interface IToggleSwitchState {
sliderPosition: ToggleSwitchPosition;
}
/**
* An example component that renders a switch whose slider position can be "left" or "right".
*/
export class ToggleSwitch extends React.Component<IToggleSwitchProps, IToggleSwitchState> {
public constructor(props: IToggleSwitchProps) {
super(props);
this.state = {
sliderPosition: ToggleSwitchPosition.Left
};
}
public render(): React.ReactNode {
const frameStyle: React.CSSProperties = {
backgroundColor:
this.state.sliderPosition === ToggleSwitchPosition.Left ? this.props.leftColor : this.props.rightColor
};
return (
<div className={styles.frame} style={frameStyle} onClick={this._onClickSlider}>
<div
className={
this.state.sliderPosition === ToggleSwitchPosition.Left ? styles.sliderLeft : styles.sliderRight
}
/>
</div>
);
}
// React event handlers should be represented as fields instead of methods to ensure the "this" pointer
// is bound correctly. This form does not work with virtual/override inheritance, so use regular methods
// everywhere else.
private _onClickSlider = (event: React.MouseEvent): void => {
if (this.state.sliderPosition === ToggleSwitchPosition.Left) {
this.setState({ sliderPosition: ToggleSwitchPosition.Right });
} else {
this.setState({ sliderPosition: ToggleSwitchPosition.Left });
}
if (this.props.onToggle) {
this.props.onToggle(this, { sliderPosition: this.state.sliderPosition });
}
};
}