Massive/Select.tsx

73 lines
1.5 KiB
TypeScript
Raw Normal View History

2022-12-30 06:39:35 +00:00
import React, {useCallback, useMemo, useState} from 'react'
import {View} from 'react-native'
2022-11-30 02:15:19 +00:00
import {Button, Menu, Subheading, useTheme} from 'react-native-paper'
import {ITEM_PADDING} from './constants'
export interface Item {
value: string
label: string
color?: string
}
2022-11-01 03:06:25 +00:00
2022-12-30 06:39:35 +00:00
function Select({
2022-11-01 03:06:25 +00:00
value,
onChange,
items,
2022-11-30 02:15:19 +00:00
label,
2022-11-01 03:06:25 +00:00
}: {
value: string
onChange: (value: string) => void
items: Item[]
2022-11-30 02:15:19 +00:00
label?: string
2022-11-01 03:06:25 +00:00
}) {
const [show, setShow] = useState(false)
const {colors} = useTheme()
const selected = useMemo(
() => items.find(item => item.value === value) || items[0],
[items, value],
)
const handlePress = useCallback(
(newValue: string) => {
onChange(newValue)
setShow(false)
},
[onChange],
)
2022-11-01 03:06:25 +00:00
return (
2022-11-30 02:15:19 +00:00
<View
style={{
flexDirection: 'row',
alignItems: 'center',
paddingLeft: ITEM_PADDING,
2022-11-30 02:15:19 +00:00
}}>
{label && <Subheading style={{width: 100}}>{label}</Subheading>}
2022-11-30 02:15:19 +00:00
<Menu
visible={show}
onDismiss={() => setShow(false)}
anchor={
<Button
onPress={() => setShow(true)}
style={{
alignSelf: 'flex-start',
}}>
{selected?.label}
</Button>
}>
{items.map(item => (
<Menu.Item
key={item.value}
titleStyle={{color: item.color || colors.text}}
title={item.label}
onPress={() => handlePress(item.value)}
/>
))}
</Menu>
</View>
2022-11-01 03:06:25 +00:00
)
}
2022-12-30 06:39:35 +00:00
export default React.memo(Select)