-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathErrorableCheckbox.jsx
More file actions
98 lines (89 loc) · 2.42 KB
/
Copy pathErrorableCheckbox.jsx
File metadata and controls
98 lines (89 loc) · 2.42 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
89
90
91
92
93
94
95
96
97
98
import PropTypes from 'prop-types';
import React from 'react';
import _ from 'lodash';
class ErrorableCheckbox extends React.Component {
constructor() {
super();
this.handleChange = this.handleChange.bind(this);
}
componentWillMount() {
this.inputId = _.uniqueId('errorable-checkbox-');
}
handleChange(domEvent) {
this.props.onValueChange(domEvent.target.checked);
}
render() {
// TODO: extract error logic into a utility function
// Calculate error state.
let errorSpan = '';
let errorSpanId = undefined;
if (this.props.errorMessage) {
errorSpanId = `${this.inputId}-error-message`;
errorSpan = (
<span className="usa-error-message" role="alert" id={errorSpanId}>
<span className="sr-only">Error</span> {this.props.errorMessage}
</span>
);
}
// Calculate required.
let requiredSpan = undefined;
if (this.props.required) {
requiredSpan = <span className="form-required-span">*</span>;
}
let className = `usa-checkbox${
this.props.errorMessage ? ' usa-input--error' : ''
}`;
if (!_.isUndefined(this.props.className)) {
className = `${className} ${this.props.className}`;
}
return (
<div className={className}>
<input
aria-describedby={errorSpanId}
checked={this.props.checked}
id={this.inputId}
name={this.props.name}
type="checkbox"
className="usa-checkbox__input"
onChange={this.handleChange}/>
<label
className={
this.props.errorMessage ? 'usa-checkbox__label usa-label--error' : 'usa-checkbox__label'
}
name={`${this.props.name}-label`}
htmlFor={this.inputId}>
{this.props.label}
{requiredSpan}
</label>
{errorSpan}
</div>
);
}
}
ErrorableCheckbox.propTypes = {
/**
* If the checkbox is checked or not
*/
checked: PropTypes.bool,
/**
* Error message for the modal
*/
errorMessage: PropTypes.string,
/**
* Name for the modal
*/
name: PropTypes.string,
/**
* Label for the checkbox
*/
label: PropTypes.oneOfType([PropTypes.string, PropTypes.object]).isRequired,
/**
* Handler for when the checkbox is changed
*/
onValueChange: PropTypes.func.isRequired,
/**
* If the checkbox is required or not
*/
required: PropTypes.bool
};
export default ErrorableCheckbox;