-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathindex.js
100 lines (85 loc) · 3.01 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
import React, {useEffect, useState} from 'react';
import {View} from 'react-native';
import lodashGet from 'lodash/get';
import PropTypes from 'prop-types';
import styles from '../../styles/styles';
import MenuItemWithTopDescription from '../MenuItemWithTopDescription';
import useLocalize from '../../hooks/useLocalize';
import FormHelpMessage from '../FormHelpMessage';
import StateSelectorModal from './StateSelectorModal';
import refPropTypes from '../refPropTypes';
const propTypes = {
/** Error text to display */
errorText: PropTypes.string,
/** State to display */
value: PropTypes.string,
/** Callback to call when the input changes */
onInputChange: PropTypes.func,
/** A ref to forward to MenuItemWithTopDescription */
forwardedRef: refPropTypes,
/** Label to display on field */
label: PropTypes.string,
};
const defaultProps = {
value: undefined,
forwardedRef: undefined,
errorText: '',
onInputChange: () => {},
label: undefined,
};
function StatePicker({value, errorText, onInputChange, forwardedRef, label}) {
const {translate} = useLocalize();
const allStates = translate('allStates');
const [isPickerVisible, setIsPickerVisible] = useState(false);
const [searchValue, setSearchValue] = useState(lodashGet(allStates, `${value}.stateName`, ''));
useEffect(() => {
setSearchValue(lodashGet(allStates, `${value}.stateName`, ''));
}, [value, allStates]);
const showPickerModal = () => {
setSearchValue(lodashGet(allStates, `${value}.stateName`, ''));
setIsPickerVisible(true);
};
const hidePickerModal = () => {
setIsPickerVisible(false);
};
const updateStateInput = (state) => {
onInputChange(state.value);
hidePickerModal();
};
const title = allStates[value] ? allStates[value].stateName : '';
const descStyle = title.length === 0 ? styles.textNormal : null;
return (
<View>
<MenuItemWithTopDescription
ref={forwardedRef}
shouldShowRightIcon
title={title}
description={label || translate('common.state')}
descriptionTextStyle={descStyle}
onPress={showPickerModal}
/>
<View style={styles.ml5}>
<FormHelpMessage message={errorText} />
</View>
<StateSelectorModal
isVisible={isPickerVisible}
currentState={value}
onClose={hidePickerModal}
onStateSelected={updateStateInput}
searchValue={searchValue}
setSearchValue={setSearchValue}
label={label}
/>
</View>
);
}
StatePicker.propTypes = propTypes;
StatePicker.defaultProps = defaultProps;
StatePicker.displayName = 'StatePicker';
export default React.forwardRef((props, ref) => (
<StatePicker
// eslint-disable-next-line react/jsx-props-no-spreading
{...props}
forwardedRef={ref}
/>
));