-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathindex.js
102 lines (86 loc) · 2.9 KB
/
index.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
import React, {useState} from 'react';
import {View} from 'react-native';
import PropTypes from 'prop-types';
import _ from 'lodash';
import styles from '../../styles/styles';
import MenuItemWithTopDescription from '../MenuItemWithTopDescription';
import ValueSelectorModal from './ValueSelectorModal';
import FormHelpMessage from '../FormHelpMessage';
import refPropTypes from '../refPropTypes';
const propTypes = {
/** Form Error description */
errorText: PropTypes.string,
/** Item to display */
value: PropTypes.string,
/** A placeholder value to display */
placeholder: PropTypes.string,
/** Items to pick from */
items: PropTypes.arrayOf(PropTypes.shape({value: PropTypes.string, label: PropTypes.string})),
/** Label of picker */
label: PropTypes.string,
/** Callback to call when the input changes */
onInputChange: PropTypes.func,
/** A ref to forward to MenuItemWithTopDescription */
forwardedRef: refPropTypes,
};
const defaultProps = {
value: undefined,
label: undefined,
placeholder: '',
items: {},
forwardedRef: undefined,
errorText: '',
onInputChange: () => {},
};
function ValuePicker({value, label, items, placeholder, errorText, onInputChange, forwardedRef}) {
const [isPickerVisible, setIsPickerVisible] = useState(false);
const showPickerModal = () => {
setIsPickerVisible(true);
};
const hidePickerModal = () => {
setIsPickerVisible(false);
};
const updateInput = (item) => {
if (item.value !== value) {
onInputChange(item.value);
}
hidePickerModal();
};
const descStyle = value.length === 0 ? styles.textNormal : null;
const selectedItem = _.find(items, {value});
const selectedLabel = selectedItem ? selectedItem.label : '';
return (
<View>
<MenuItemWithTopDescription
ref={forwardedRef}
shouldShowRightIcon
title={selectedLabel || placeholder || ''}
descriptionTextStyle={descStyle}
description={label}
onPress={showPickerModal}
/>
<View style={styles.ml5}>
<FormHelpMessage message={errorText} />
</View>
<ValueSelectorModal
isVisible={isPickerVisible}
currentValue={selectedLabel || placeholder || ''}
label={label}
selectedItem={selectedItem}
items={items}
onClose={hidePickerModal}
onItemSelected={updateInput}
/>
</View>
);
}
ValuePicker.propTypes = propTypes;
ValuePicker.defaultProps = defaultProps;
ValuePicker.displayName = 'ValuePicker';
export default React.forwardRef((props, ref) => (
<ValuePicker
// eslint-disable-next-line react/jsx-props-no-spreading
{...props}
forwardedRef={ref}
/>
));