-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathClearableInput.js
More file actions
124 lines (106 loc) · 2.29 KB
/
ClearableInput.js
File metadata and controls
124 lines (106 loc) · 2.29 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
122
123
124
import React, { Component } from 'react'
import styled from 'styled-components'
export default class ClearableInput extends Component {
static defaultProps = {
error: false,
placeholder: '',
immediate: true,
onBlur: () => {},
onChange: () => {}
}
state = {
value: ''
}
initRef = ref => (this.input = ref)
handleChange = e => {
const { immediate, onChange } = this.props
const value = e.target ? e.target.value : e
this.setState({ value })
if (immediate) {
onChange(value)
}
}
handleKeyDown = e => {
const { onChange } = this.props
if (e.keyCode === 13) {
onChange(this.state.value)
}
}
clear = () => {
const { onChange } = this.props
const value = ''
this.setState({ value })
onChange(value)
}
blur = () => {
this.props.onBlur(this.state.value)
}
onFocus() {
this.input.focus()
}
componentWillReceiveProps(nextProps) {
if (this.props.value !== nextProps.value) {
this.setState({ value: nextProps.value })
}
}
componentDidMount() {
if (this.props.autoFocus) {
this.props.autoFocus && this.onFocus()
}
this.state.value = this.props.value
}
isEmpty = () => this.state.value.trim() === ''
render() {
const { error, placeholder } = this.props
const { value } = this.state
return (
<Wrapper error={error}>
<Input
ref={this.initRef}
value={value}
placeholder={placeholder}
onBlur={this.blur}
onChange={this.handleChange}
onKeyDown={this.handleKeyDown}
/>
{!this.isEmpty() && <Close onClick={this.clear}>×</Close>}
</Wrapper>
)
}
}
export const Wrapper = styled.div`
width: 100%;
position: relative;
background: #fff;
border: 1px solid #d7d9d9;
border-radius: 4px;
overflow: hidden;
width: 100%;
display: flex;
${props =>
props.error &&
`
color: indianred;
`};
`
export const Input = styled.input`
flex: 1;
padding: 8px 26px 8px 16px;
border: none;
`
const Close = styled.button`
position: absolute;
right: 10px;
top: 7px;
width: 16px;
border: none;
color: #999;
text-align: center;
padding: 0px;
font-size: 18px;
text-align: center;
vertical-align: top;
&:hover {
color: #d0021b;
}
`