dimanche 8 mai 2022

checkboxes and state react-native

Im newbie who tries react native cant handle multiple checkboxes list and object state. i mean i need to change boolen prop in data (bool:) by pressing on certain checkbox.

what should i write in onPress? and do i need to use useEffect to re-render list? thank all beforehead!

data in useState

{
    title: "title1", 
    checkboxes: [
        {key:1, value: 1, bool: false,
            text: 'never'},
        {key:2, value: 1, bool: true,
            text: 'gonna'},
        {key:3, value: 2, bool: true,
            text: 'give'},
        {key:4, value: 2, bool: false,
            text: 'you'},
        {key:5, value: 3, bool: false,
            text: 'up'},
        {key:6, value: 4, bool: false,
            text: 'never'},
        ],
    },

react-native code

import React, {useEffect, useState, useReducer} from 'react';
import { View, Image, ImageBackground } from 'react-native';
import { useDispatch, useSelector } from 'react-redux';

import { Text, Button, CheckBox } from 'react-native-elements'; 
import { TouchableOpacity } from 'react-native-gesture-handler';
import * as functions from './helpers/functions';


export default function CheckListScreen (): JSX.Element {
  
  const [testData, setTestData] = useState(data); 
  
/* tried that 
  const [state, updateState] = useReducer(
    (state: any, updates: any) => ({
      ...state,
      ...updates,
    }),
    testData
  );*/

  return(
    <View style={styles.container}>
      
        <View style=>
          <Text style={styles.title}>{testData.title.toUpperCase()}</Text>
        </View>

        <View style=>
        {testData.checkboxes.map((item, key)=> //
          <View key={item.key} style={styles.checkbox}>
            <CheckBox 
            checked={item.bool}
            //onPress={updateState({testData})}
            //onPress={setCheckbox({...checkbox, checkbox[key] = true})}
            //onPress={setTestData(testData.checkboxes.map(()=>testData.checkboxes[key].bool = true))}
            //onPress={setTestData(()=> ({...item, item[key].bool = true}))} // testData.checkboxes[key].bool = true
            >
            </CheckBox>
            <Text style={styles.textCheckbox}>{item.text.toUpperCase()}</Text>
          </View>)}
        </View>
    </View>
  );
}



Aucun commentaire:

Enregistrer un commentaire