0

I'm trying implement react-native-elements checkbox. In my case i need to have multiple checkbox based on the array. Below is my code -

const CheckTest = () => {
    const [check, setCheck] = useState(false);
    const label = [
        {
            name: 'first'
        },
        {
            name: 'second'
        },
        {
            name: 'third'
        },
        {
            name: 'fourth'
        }]
    const onValueChange = () => {
        setCheck(check => !check)
    }
    return (
        <View style={{ paddingTop: 20 }}>
            {label.map(item => {
                return <CheckBox
                    title={item.name}
                    checked={check}
                    onPress={(val) => onValueChange(val)}
                    key={item.name}
                />
            })}


        </View>
    )
}

Problem is in this code is when i select/deselect one checkbox all checkbox are getting checked/unchecked.

I aasume this is happening because of check state as it is applying to all.

How to handle this scnario?

Thanks in advance !!!!!

1 Answer 1

0

Try this way

const CheckTest = () => {
    const [data, setData] = useState([
        {
            name: 'first'
        },
        {
            name: 'second'
        },
        {
            name: 'third'
        },
        {
            name: 'fourth'
        }]); 



    const onValueChange = (item, index) => {
        const newData = [...data];
        newData[index].isCheck = !item.isCheck;
        setData(newData);
    }

    return (
        <View style={{ paddingTop: 20 }}>
            {data.map((item, index) => {
                return <CheckBox
                    title={item.name}
                    checked={item.isCheck || false}
                    onPress={(val) => onValueChange(item, index)}
                    key={item.name}
                />
            })}


        </View>
    )
}
Sign up to request clarification or add additional context in comments.

5 Comments

what is item.ischeck here
ischeck is a key here like name and we're defining it on runtime so it would work surely. You can also define it in [{name: 'first', ischeck: false },...]
this data is coming from a API, do i need to add ischeck in the api data?
No, of course not. You can do this on runtime as I answered
@NooruddinLakhani i am having same problem exactly but this solution doesn't work for me TypeError: undefined is not an object (evaluating 'newData[index].isCheck = !item.isCheck')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.