SelectInput.tsx 1.89 KB
Newer Older
1
2
3
4
5
import React from 'react';
import { StyleSheet, ViewStyle } from 'react-native';
import SelectDowndown from 'react-native-select-dropdown';
import { capitalize } from '../../utils/textTransform';
import { useThemeColor } from './Themed';
6
7
type IProps<T> = {
  data: T[];
8
  style?: ViewStyle;
9
10
11
12
  defaultValue?: string;
  onChange?: (value: T | null) => void;
};

13
14
15
/**
 * Input for selecting an item in a list with a dropdown menu
 */
16
function SelectInput<T extends string>(props: IProps<T>) {
17
18
19
20
21
22
23
  const { defaultValue, onChange } = props;
  let { data } = props;

  // Append default value if it's defined
  if (defaultValue) {
    data = [defaultValue as T, ...data];
  }
24
25
26
27

  // Return 'null' if default value is selected
  function dispatchValue(value: T | string) {
    if (onChange) {
28
      onChange(value === defaultValue ? null : (value.toLowerCase() as T));
29
30
31
32
    }
  }

  return (
33
34
35
36
37
    <SelectDowndown
      buttonStyle={[
        styles.button,
        props.style,
        {
38
39
          backgroundColor: useThemeColor({}, 'component'),
          borderColor: useThemeColor({}, 'border'),
40
41
        },
      ]}
42
      buttonTextStyle={[styles.text, { color: useThemeColor({}, 'inputText') }]}
43
      dropdownStyle={{
44
        backgroundColor: useThemeColor({}, 'component'),
45
      }}
46
      rowStyle={{minHeight: 40, borderColor: useThemeColor({}, 'border') }}
47
      rowTextStyle={[styles.text, { color: useThemeColor({}, 'inputText') }]}
48
49
50
51
52
53
      data={data}
      onSelect={(selected) => dispatchValue(selected)}
      defaultValueByIndex={0}
      buttonTextAfterSelection={(selected, index) => capitalize(selected)}
      rowTextForSelection={(item) => capitalize(item)}
    />
54
55
56
57
  );
}

const styles = StyleSheet.create({
58
59
60
61
  button: {
    height: 40,
    maxWidth: 100,
    borderWidth: 1,
62
    borderRadius: 15,
63
64
65
66
67
68
    padding: 0,
  },
  text: {
    paddingVertical: 0,
    marginVertical: 0,
    fontSize: 14,
69
70
71
72
  },
});

export default SelectInput;