/
Button.js
100 lines (85 loc) · 2.16 KB
/
Button.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
95
96
97
98
99
100
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { mapToCssModules, tagPropType } from './utils';
const propTypes = {
active: PropTypes.bool,
'aria-label': PropTypes.string,
block: PropTypes.bool,
color: PropTypes.string,
disabled: PropTypes.bool,
outline: PropTypes.bool,
tag: tagPropType,
innerRef: PropTypes.oneOfType([PropTypes.object, PropTypes.func, PropTypes.string]),
onClick: PropTypes.func,
size: PropTypes.string,
children: PropTypes.node,
className: PropTypes.string,
cssModule: PropTypes.object,
close: PropTypes.bool,
};
const defaultProps = {
color: 'secondary',
tag: 'button',
};
class Button extends React.Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
}
onClick(e) {
if (this.props.disabled) {
e.preventDefault();
return;
}
if (this.props.onClick) {
return this.props.onClick(e);
}
}
render() {
let {
active,
'aria-label': ariaLabel,
block,
className,
close,
cssModule,
color,
outline,
size,
tag: Tag,
innerRef,
...attributes
} = this.props;
if (close && typeof attributes.children === 'undefined') {
attributes.children = <span aria-hidden>×</span>;
}
const btnOutlineColor = `btn${outline ? '-outline' : ''}-${color}`;
const classes = mapToCssModules(classNames(
className,
close && 'btn-close',
close || 'btn',
close || btnOutlineColor,
size ? `btn-${size}` : false,
block ? 'btn-block' : false,
{ active, disabled: this.props.disabled }
), cssModule);
if (attributes.href && Tag === 'button') {
Tag = 'a';
}
const defaultAriaLabel = close ? 'Close' : null;
return (
<Tag
type={(Tag === 'button' && attributes.onClick) ? 'button' : undefined}
{...attributes}
className={classes}
ref={innerRef}
onClick={this.onClick}
aria-label={ariaLabel || defaultAriaLabel}
/>
);
}
}
Button.propTypes = propTypes;
Button.defaultProps = defaultProps;
export default Button;