Massive/Select.tsx

75 lines
1.5 KiB
TypeScript
Raw Normal View History

2023-06-27 03:16:59 +00:00
import React, { useCallback, useMemo, useState } from 'react'
import { View } from 'react-native'
import { Button, Menu, Subheading } from 'react-native-paper'
2023-06-27 03:16:59 +00:00
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 selected = useMemo(
2023-06-27 03:16:59 +00:00
() => 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,
2023-06-27 03:16:59 +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',
2023-06-27 03:16:59 +00:00
}}
>
2022-11-30 02:15:19 +00:00
{selected?.label}
</Button>
2023-06-27 03:16:59 +00:00
}
>
{items.map((item) => (
2022-11-30 02:15:19 +00:00
<Menu.Item
titleStyle={{ color: item.color }}
2022-11-30 02:15:19 +00:00
key={item.value}
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)