forked from aaronshaf/react-toggle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.es6.js
94 lines (82 loc) · 2.2 KB
/
index.es6.js
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
89
90
91
92
93
94
import React from 'react'
import classNames from 'classnames'
import Check from './check'
import X from './x'
import PureRenderMixin from 'react-addons-pure-render-mixin'
export default React.createClass({
mixins: [PureRenderMixin],
displayName: 'Toggle',
propTypes: {
checked: React.PropTypes.bool,
defaultChecked: React.PropTypes.bool,
onChange: React.PropTypes.func,
name: React.PropTypes.string,
value: React.PropTypes.string,
id: React.PropTypes.string,
'aria-labelledby': React.PropTypes.string,
'aria-label': React.PropTypes.string
},
getInitialState() {
var checked = false;
if ('checked' in this.props) {
checked = this.props.checked
} else if ('defaultChecked' in this.props) {
checked = this.props.defaultChecked
}
return {
checked: !!checked,
hasFocus: false
}
},
componentWillReceiveProps(nextProps) {
if ('checked' in nextProps) {
this.setState({checked: !!nextProps.checked})
}
},
handleClick(event) {
var checkbox = this.refs.input
if (event.target !== checkbox)
{
event.preventDefault()
checkbox.focus()
checkbox.click()
return
}
if (!('checked' in this.props)) {
this.setState({checked: checkbox.checked})
}
},
handleFocus() {
this.setState({hasFocus: true})
},
handleBlur() {
this.setState({hasFocus: false})
},
render() {
var classes = classNames('react-toggle', {
'react-toggle--checked': this.state.checked,
'react-toggle--focus': this.state.hasFocus,
'react-toggle--disabled': this.props.disabled
})
return (
<div className={classes} onClick={this.handleClick}>
<div className="react-toggle-track">
<div className="react-toggle-track-check">
<Check />
</div>
<div className="react-toggle-track-x">
<X />
</div>
</div>
<div className="react-toggle-thumb"></div>
<input
ref="input"
onFocus={this.handleFocus}
onBlur={this.handleBlur}
className="react-toggle-screenreader-only"
type="checkbox"
{...this.props} />
</div>
)
}
})