I have a component which changes the state when checkbox is checked and the data needs to be updated of the object in the array.
The component state looks something like this { key:1, todo:”Something”, isChecked:false }
i have 3 files: AddTodo.js Which passes state & setState to an component TodoList which passes it the subcomponent TodoItem.
I am unable to update the state from TodoItem , I need to implement a function that finds the object from array and updates its isChecked state.
AddTodo.js
function AddTodo() { const [state, setState] = useState(false); const [todos, addTodos] = useState([]); var keys = (todos || []).length; return ( <View style={styles.container}> <Modal animationType="slide" transparent={true} visible={state} statusBarTranslucent={true} > <View style={styles.itemsContainer}> <GetInfoDialog state={state} stateChange={setState} addItem={addTodos} numKeys={keys} /> </View> </Modal> {(todos || []).length > 0 ? ( <TodoList data={todos} updateState={addTodos} /> ) : null} <TouchableOpacity style={styles.btn} onPress={() => { setState(true); }} > <Text style={styles.text}>Add New</Text> </TouchableOpacity> </View> ); }
TodoList.js
function TodoList(props) { return ( <View style={styles.todoList}> <FlatList data={props.data} renderItem={({ item }) => { console.log(item); return ( <TodoItem list={props.data} itemKey={item.key} todo={item.todo} isChecked={item.isChecked} updateState={props.updateState} /> ); }} backgroundColor={"#000000"} alignItems={"center"} justifyContent={"space-between"} /> </View> ); }
TodoItem.js
function TodoItem(props) { const [checked, setCheck] = useState(props.isChecked); return ( <View style={styles.todoItem}> <Checkbox value={checked} onValueChange={() => { setCheck(!checked); }} style={styles.checkbox} /> <Text style={styles.text}>{props.todo}</Text> </View> ); }
Advertisement
Answer
renderItem={({ item, index }) => { console.log(item); return ( <TodoItem list={props.data} itemKey={item.key} todo={item.todo} isChecked={item.isChecked} updateState={props.updateState} setChecked={(value)=>{ let updatedList = [...yourTodosList] updatedlist[index].isChecked=value setTodos(updatedList) }} /> ); }}
and in your todo item
onValueChange={(value) => { props.setChecked(value); }}
i also don’t think that you need an is checked state in your todo component since you are passing that through props (so delete const [checked, setCheck] = useState(props.isChecked)
line and just use the value you are getting from props.isChecked)
didn’t pay much attention to your variable names but this should put you on the right track