How to count selected checkboxes in React Native in functional component?



Whole code is here

I render two flat list, One shows category name and other shows its sub categories with check box. Now i want, when user checked multiple or one check box of the sub catogories, The count shows in category like Health(count = 2) is category: if i checked pharmacy and hopital. 1 pharmacy 2 hospital 3 nurse

import React, { useState } from "react";
import { View, Text, Dimensions } from "react-native";
var { width } = Dimensions.get("window");
import {CheckBox} from 'native-base';

 const CategoriesList = ({item}) => {
  const [checked, setChecked] = useState(false)
   const [selected,setSelected] = useState([0]);

   function onChange( items) {
     if (checked==false) {
      setSelected([...selected, items]);
    }
    
    else {
     setSelected((prev) =>
        prev.filter((currItem) => currItem.category !== items.name)
       );
   }
   }
  

   const ToggleCheck = () => {
       setChecked(!checked)
   }
  



  return (
    <View
      style={{
        backgroundColor: "white",
        padding: 10,
        flexDirection: "row",
        width: width,
      }}
    >
      <Text
        style={{
          fontWeight: "bold",
          color: "black",
          alignSelf: "center",
          flexGrow: 1,
          marginHorizontal: 10,
        }}
      >
        
        {item.name}
      
      
      
        
      
          <CheckBox color='#B50900' checked={checked} onPress={(checked)=>{onChange(checked),ToggleCheck()}} /> 

          <Text>{selected.length > 0 ? selected.length : null}  </Text>
 
                   
                             
      
        
      </Text>
      
    </View>
  )}

export default CategoriesList

I want to achieve same logic in React Native, you can check by clicking on link https://codesandbox.io/s/react-playground-forked-co324?file=/index.js

Answer

This is the same react link that you have provided but using react native.

It may not seems to work on codesandbox because it uses react native web. but it should work on react native app.

https://codesandbox.io/s/blissful-paper-hcyfc?file=/src/App.js



Source: stackoverflow