|
| 1 | +import * as React from "react"; |
| 2 | +import { View, StyleProp, ViewStyle } from "react-native"; |
| 3 | +import { PureRoundedCheckbox } from "react-native-rounded-checkbox"; |
| 4 | +import { IRoundedCheckboxProps } from "react-native-rounded-checkbox/build/dist/functional/RoundedCheckbox"; |
| 5 | +import useStateWithCallback from "./helpers/useStateWithCallback"; |
| 6 | +/** |
| 7 | + * ? Local Imports |
| 8 | + */ |
| 9 | +import styles from "./RoundedCheckboxGroup.style"; |
| 10 | + |
| 11 | +type CustomStyleProp = StyleProp<ViewStyle> | Array<StyleProp<ViewStyle>>; |
| 12 | + |
| 13 | +export interface ICheckboxButton extends IRoundedCheckboxProps { |
| 14 | + id: number; |
| 15 | +} |
| 16 | + |
| 17 | +export interface IRoundedCheckboxGroupProps { |
| 18 | + style?: CustomStyleProp; |
| 19 | + initial?: number; |
| 20 | + children?: React.ReactNode; |
| 21 | + data: ICheckboxButton[]; |
| 22 | + component?: (isActive: boolean) => React.ReactNode; |
| 23 | + onChange: (selectedItem: ICheckboxButton) => void; |
| 24 | +} |
| 25 | + |
| 26 | +const RoundedCheckboxGroup: React.FC<IRoundedCheckboxGroupProps> = ({ |
| 27 | + style, |
| 28 | + data, |
| 29 | + initial, |
| 30 | + children, |
| 31 | + component, |
| 32 | + onChange, |
| 33 | +}) => { |
| 34 | + const [selectedItem, setSelectedItem] = useStateWithCallback< |
| 35 | + ICheckboxButton | undefined |
| 36 | + >(undefined); |
| 37 | + |
| 38 | + const handleItemPress = (item: ICheckboxButton) => { |
| 39 | + setSelectedItem(item, (newItem) => onChange && onChange(newItem)); |
| 40 | + }; |
| 41 | + |
| 42 | + return ( |
| 43 | + <View style={[styles.container, style]}> |
| 44 | + {data && |
| 45 | + data.map((item: ICheckboxButton) => { |
| 46 | + const isActive = |
| 47 | + item.id === (selectedItem ? selectedItem?.id : initial); |
| 48 | + return ( |
| 49 | + <PureRoundedCheckbox |
| 50 | + {...item} |
| 51 | + key={item.id} |
| 52 | + active={isActive} |
| 53 | + onPress={() => handleItemPress(item)} |
| 54 | + > |
| 55 | + {component ? component(isActive) : children} |
| 56 | + </PureRoundedCheckbox> |
| 57 | + ); |
| 58 | + })} |
| 59 | + </View> |
| 60 | + ); |
| 61 | +}; |
| 62 | + |
| 63 | +export default RoundedCheckboxGroup; |
0 commit comments