-
Notifications
You must be signed in to change notification settings - Fork 0
/
Select.tsx
105 lines (90 loc) · 1.83 KB
/
Select.tsx
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
import React, {
SelectHTMLAttributes,
Ref,
ReactNode,
ReactElement,
ChangeEvent,
PureComponent,
Children
} from 'react';
import PropTypes from 'prop-types';
import {
CombinePropsAndAttributes,
Bind,
omit
} from '../../helpers';
import {
Primitive,
PrimitivePropType
} from '../common/types';
import {
style,
classes
} from './Select.st.css';
export * from './SelectOption';
interface ISelfProps {
elementRef?: Ref<HTMLSelectElement>;
defaultValue?: Primitive;
value?: Primitive;
children: ReactNode;
onChange?(value: Primitive, event: ChangeEvent);
}
export type IProps = CombinePropsAndAttributes<
ISelfProps,
SelectHTMLAttributes<HTMLSelectElement>
>;
export default class Select extends PureComponent<IProps> {
static propTypes = {
elementRef: PropTypes.func,
defaultValue: PrimitivePropType,
value: PrimitivePropType,
onChange: PropTypes.func,
children: PropTypes.node.isRequired
};
private originalValues: Primitive[] = [];
render() {
const {
className,
elementRef,
defaultValue,
value,
children,
...props
} = this.props;
this.originalValues = Children.toArray(children).map(({
props: {
value,
children
}
}: ReactElement<any>) => (
typeof value === 'undefined'
? children
: value
));
return (
<select
ref={elementRef}
{...omit(props, ['multiple'])}
className={style(classes.root, className)}
onChange={this.onChange}
defaultValue={defaultValue as string}
value={value as string}
>
{children}
</select>
);
}
@Bind()
onChange(event: ChangeEvent<HTMLSelectElement>) {
const {
onChange
} = this.props;
if (typeof onChange === 'function') {
const {
selectedIndex
} = event.currentTarget.options;
const nextValue = this.originalValues[selectedIndex];
onChange(nextValue, event);
}
}
}