|
| 1 | +import React, { useEffect, useState } from "react"; |
| 2 | +import { SafeAreaView, FlatList, Text, View } from "react-native"; |
| 3 | +import BouncyCheckbox from "react-native-bouncy-checkbox"; |
| 4 | + |
| 5 | +type ICheckboxComponent = { |
| 6 | + id: string; |
| 7 | + title: string; |
| 8 | +}; |
| 9 | + |
| 10 | +type IItem = { |
| 11 | + item: ICheckboxComponent; |
| 12 | +}; |
| 13 | + |
| 14 | +const generateToggleState = ( |
| 15 | + array: ICheckboxComponent[], |
| 16 | + key: string, |
| 17 | + value: boolean, |
| 18 | +) => { |
| 19 | + if (!array) return []; |
| 20 | + const initialValue = {}; |
| 21 | + return array.reduce((obj, item) => { |
| 22 | + // @ts-ignore |
| 23 | + return item[key] |
| 24 | + ? { |
| 25 | + ...obj, |
| 26 | + // @ts-ignore |
| 27 | + [item[key].replace(/\s/, "")]: value, |
| 28 | + } |
| 29 | + : obj; |
| 30 | + }, initialValue); |
| 31 | +}; |
| 32 | + |
| 33 | +const MultipleCheckboxes = () => { |
| 34 | + const itemList = [ |
| 35 | + { id: "checkbox-1", title: "First checkbox" }, |
| 36 | + { id: "checkbox-2", title: "Second checkbox" }, |
| 37 | + { id: "checkbox-3", title: "Third checkbox" }, |
| 38 | + { id: "checkbox-4", title: "Forth checkbox" }, |
| 39 | + ]; |
| 40 | + |
| 41 | + const [toggleCheckbox, setToggleCheckbox] = useState<any>({}); |
| 42 | + |
| 43 | + const handleToggleState = (item: ICheckboxComponent) => |
| 44 | + setToggleCheckbox({ |
| 45 | + ...toggleCheckbox, |
| 46 | + [item.id]: !toggleCheckbox[item.id], |
| 47 | + }); |
| 48 | + |
| 49 | + useEffect(() => { |
| 50 | + setToggleCheckbox(generateToggleState(itemList, "id", false)); |
| 51 | + }, []); |
| 52 | + |
| 53 | + const CheckboxComponent = ({ item }: IItem) => { |
| 54 | + const { id, title } = item; |
| 55 | + return ( |
| 56 | + <BouncyCheckbox |
| 57 | + disableBuiltInState |
| 58 | + fillColor="red" |
| 59 | + iconStyle={{ borderColor: "red" }} |
| 60 | + isChecked={toggleCheckbox[id]} |
| 61 | + key={id} |
| 62 | + onPress={() => handleToggleState({ id, title })} |
| 63 | + style={{ paddingBottom: 10 }} |
| 64 | + text={title} |
| 65 | + textStyle={{ textDecorationLine: "none" }} |
| 66 | + /> |
| 67 | + ); |
| 68 | + }; |
| 69 | + |
| 70 | + const renderItem = ({ item }: IItem) => <CheckboxComponent item={item} />; |
| 71 | + |
| 72 | + return ( |
| 73 | + <View> |
| 74 | + <Text>Toggle multiple checkboxes</Text> |
| 75 | + <SafeAreaView |
| 76 | + style={{ |
| 77 | + marginTop: 10, |
| 78 | + height: 140, |
| 79 | + }} |
| 80 | + > |
| 81 | + <FlatList |
| 82 | + data={itemList} |
| 83 | + renderItem={renderItem} |
| 84 | + keyExtractor={(item) => item.id} |
| 85 | + style={{ padding: 2 }} |
| 86 | + /> |
| 87 | + </SafeAreaView> |
| 88 | + </View> |
| 89 | + ); |
| 90 | +}; |
| 91 | + |
| 92 | +export default MultipleCheckboxes; |
0 commit comments