-
Notifications
You must be signed in to change notification settings - Fork 374
/
Copy pathFieldSelect.js
103 lines (86 loc) · 2.64 KB
/
FieldSelect.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
101
102
103
import React from 'react';
import { func, node, object, string } from 'prop-types';
import { Field } from 'react-final-form';
import classNames from 'classnames';
import { ValidationError } from '../../components';
import css from './FieldSelect.module.css';
const handleChange = (propsOnChange, inputOnChange) => event => {
// If "onChange" callback is passed through the props,
// it can notify the parent when the content of the input has changed.
if (propsOnChange) {
// "handleChange" function is attached to the low level <select> component
// value of the element needs to be picked from target
const value = event.nativeEvent.target.value;
propsOnChange(value);
}
// Notify Final Form that the input has changed.
// (Final Form knows how to deal with synthetic events of React.)
inputOnChange(event);
};
const FieldSelectComponent = props => {
const {
rootClassName,
className,
selectClassName,
id,
label,
input,
meta,
children,
onChange,
...rest
} = props;
if (label && !id) {
throw new Error('id required when a label is given');
}
const { valid, invalid, touched, error } = meta;
// Error message and input error styles are only shown if the
// field has been touched and the validation has failed.
const hasError = touched && invalid && error;
const selectClasses = classNames(selectClassName, css.select, {
[css.selectSuccess]: input.value && valid,
[css.selectError]: hasError,
});
const { onChange: inputOnChange, ...restOfInput } = input;
const selectProps = {
className: selectClasses,
id,
onChange: handleChange(onChange, inputOnChange),
...restOfInput,
...rest,
};
const classes = classNames(rootClassName || css.root, className);
return (
<div className={classes}>
{label ? <label htmlFor={id}>{label}</label> : null}
<select {...selectProps}>{children}</select>
<ValidationError fieldMeta={meta} />
</div>
);
};
FieldSelectComponent.defaultProps = {
rootClassName: null,
className: null,
selectClassName: null,
id: null,
label: null,
children: null,
};
FieldSelectComponent.propTypes = {
rootClassName: string,
className: string,
selectClassName: string,
onChange: func,
// Label is optional, but if it is given, an id is also required so
// the label can reference the input in the `for` attribute
id: string,
label: string,
// Generated by final-form's Field component
input: object.isRequired,
meta: object.isRequired,
children: node,
};
const FieldSelect = props => {
return <Field component={FieldSelectComponent} {...props} />;
};
export default FieldSelect;