Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make dynamic checkbox in react native

Tags:

react-native

I am making a react native application in which i need to make checkbox during runtime.I means that from server i will get the json object which will have id and label for checkbox.Now i want to know that after fetching data from server how can i make checkbox also how can i handle the checkbox , i mean that how many number of checkbox will be there it will not be static so how can i declare state variables which can handle the checkbox.Also how can i handle the onPress event of checkbox.Please provide me some help of code .Thanks in advance

like image 841
Abhi Singh Avatar asked Jan 27 '23 14:01

Abhi Singh


1 Answers

The concept will be using an array in the state and setting the state array with the data you got from the service response, Checkbox is not available in both platforms so you will have to use react-native-elements. And you can use the map function to render the checkboxes from the array, and have an onPress to change the state accordingly. The code will be as below. You will have to think about maintaining the checked value in the state as well.

import React, { Component } from 'react';
import { View } from 'react-native';
import { CheckBox } from 'react-native-elements';

export default class Sample extends Component {

    constructor(props) {
        super(props);
        this.state = {
            data: [
                { id: 1, key: 'test1', checked: false },
                { id: 2, key: 'test1', checked: true }
            ]
        };
    }

    onCheckChanged(id) {
        const data = this.state.data;

        const index = data.findIndex(x => x.id === id);
        data[index].checked = !data[index].checked;
        this.setState(data);
    }

    render() {
        return (<View>
            {
                this.state.data.map((item,key) => <CheckBox title={item.key} key={key}  checked={item.checked} onPress={()=>this.onCheckChanged(item.id)}/>)
            }
        </View>)
    }
}
like image 59
Guruparan Giritharan Avatar answered Jan 29 '23 04:01

Guruparan Giritharan