CheckBox value trigger complete function. React Native

Viewed 44

I am trying to make a to do list using React Native. How can I run the props.completeFunction() when the checkbox is selected or the value is set to true.

Also, how can I check whether the props.item.completed is true so that the checkbox value will set to true.

I am not good on syntaxes on React Native so I am asking you this. Thank you

import React, {useState} from 'react';
import {Text, TouchableOpacity, CheckBox} from 'react-native';
export default function TodoItem(props) {
    // Update style according to props
    let style = props.item.completed ? {
        textDecorationLine: 'line-through'
    } : {
        textDecorationLine: 'none'
    }

    const [isSelected, setSelection] = useState(false);
    return (
        <TouchableOpacity
            onLongPress={() => props.deleteFunction()}
            style={{paddingVertical: 8, flexDirection: 'row', justifyContent: 'space-between'}}>
            <Text style={[{fontSize: 18}, style]}>{props.item.text}</Text>

            <CheckBox
            value={isSelected}
            onValueChange={setSelection}
            />
            

        </TouchableOpacity>
    );
}

2 Answers

We can call a function within onValueChange. so you can try to change it as:

onValueChange={() => {setSelection(!isSelected); isSelected && props.completeFunction()}

Solved: by adding onChange = {() => props.completeFunction()} it solved the problem. The strike-through text decoration line now comes with the value of CheckBox.

Related