-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathon-click.js
More file actions
121 lines (103 loc) · 2.61 KB
/
on-click.js
File metadata and controls
121 lines (103 loc) · 2.61 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import React, { Component, PropTypes } from 'react';
import toCSS from 'style-to-css';
import uniqueId from 'mini-unique-id';
export default class OnClick extends Component {
constructor(...args) {
super(...args)
this.state = {}
}
componentWillMount() {
const { props } = this
const manualActive = typeof props.isActive === 'boolean'
this.setState({
isActive: manualActive ? props.isActive : false,
manualActive
});
this.bindOnClick(props.onClick);
}
componentWillReceiveProps(nextProps) {
this.bindOnClick(nextProps.onClick);
const manualActive = typeof nextProps.isActive === 'boolean'
if (manualActive) {
this.setState({
isActive: nextProps.isActive,
manualActive
})
}
}
componentWillUnmount() {
if (this.onClickTimeout) {
clearTimeout(this.onClickTimeout);
}
}
bindOnClick(onClick) {
/* eslint-disable no-console */
const finalOnClick = typeof onClick === 'function' ? onClick : () => console.log(onClick);
this.onClick = event => {
finalOnClick(event);
event.stopPropagation();
if (!this.state.manualActive) {
this.setState({
isActive: true
});
this.onClickTimeout = setTimeout(() => {
this.setState({
isActive: false
});
this.onClickTimeout = null;
}, this.props.styleActiveTimeout);
}
};
}
render() {
const { isActive } = this.state;
/* eslint-disable no-unused-vars */
const {
children, className, isActive: _isActive, _ref, style, styleActive, styleActiveTimeout,
styleHover, ...rest
} = this.props;
let inlineStyle = null
if (!isActive && Object.keys(styleHover).length) {
inlineStyle = <style>{`.${className}:hover {${toCSS(styleHover)}}`}</style>;
}
const finalStyle = isActive ? {
...style,
...styleActive,
outline: 0
} : {
...style,
outline: 0,
cursor: 'pointer'
};
if (_ref) {
rest.ref = _ref;
}
return (
<button
{...rest}
className={className}
disabled={isActive}
onClick={this.onClick}
style={finalStyle}
>
{inlineStyle}
{children}
</button>
);
}
}
OnClick.defaultProps = {
styleActiveTimeout: 1000
};
OnClick.propTypes = {
isActive: PropTypes.bool,
onClick: PropTypes.oneOfType([
PropTypes.func,
PropTypes.string
]),
_ref: PropTypes.func,
style: PropTypes.object,
styleActive: PropTypes.object,
styleActiveTimeout: PropTypes.number.isRequired,
styleHover: PropTypes.object
};