forked from ziad-saab/react-checkbox-group
-
Notifications
You must be signed in to change notification settings - Fork 0
/
react-checkbox-group.jsx
79 lines (67 loc) · 2.26 KB
/
react-checkbox-group.jsx
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
/**
* @jsx React.DOM
*/
var React = require('react');
module.exports = React.createClass({
displayName: 'CheckboxGroup',
getInitialState: function() {
return {defaultValue: this.props.defaultValue || []};
},
componentDidMount: function() {
this.setCheckboxNames();
this.setCheckedBoxes();
},
componentDidUpdate: function() {
this.setCheckboxNames();
this.setCheckedBoxes();
},
render: function() {
let {name, value, defaultValue, ...otherProps} = this.props;
return (
<div {...otherProps}>
{this.props.children}
</div>
);
},
setCheckboxNames: function() {
// stay DRY and don't put the same `name` on all checkboxes manually. Put it on
// the tag and it'll be done here
let $checkboxes = this.getCheckboxes();
for (let i = 0, length = $checkboxes.length; i < length; i++) {
$checkboxes[i].setAttribute('name', this.props.name);
}
},
getCheckboxes: function() {
return React.findDOMNode(this).querySelectorAll('input[type="checkbox"]');
},
setCheckedBoxes: function() {
let $checkboxes = this.getCheckboxes();
// if `value` is passed from parent, always use that value. This is similar
// to React's controlled component. If `defaultValue` is used instead,
// subsequent updates to defaultValue are ignored. Note: when `defaultValue`
// and `value` are both passed, the latter takes precedence, just like in
// a controlled component
let destinationValue = this.props.value != null
? this.props.value
: this.state.defaultValue;
for (let i = 0, length = $checkboxes.length; i < length; i++) {
let $checkbox = $checkboxes[i];
// intentionally use implicit conversion for those who accidentally used,
// say, `valueToChange` of 1 (integer) to compare it with `value` of "1"
// (auto conversion to valid html value from React)
if (destinationValue.indexOf($checkbox.value) >= 0) {
$checkbox.checked = true;
}
}
},
getCheckedValues: function() {
let $checkboxes = this.getCheckboxes();
let checked = [];
for (let i = 0, length = $checkboxes.length; i < length; i++) {
if ($checkboxes[i].checked) {
checked.push($checkboxes[i].value);
}
}
return checked;
}
});