Search code examples
react-nativereact-native-listview

In React-native, how to handle checkbox in Listview?


In my react-native app, I am trying to show my contact details with checkboxes for selecting.

Here is my code:

<ListView
    dataSource={this.state.dataSource}
    renderRow={(rowData, sectionID, rowID) => (
        <TouchableHighlight onPress={() => this.goRideDetails(rowData)}>
            <Text style={styles.rideHeader}>{rowData.name} </Text>
            <CheckBox
                checked={this.state.checked}
                onCheckBoxPressed={() =>
                    this.setState({ checked: !this.state.checked })
                }
            />
        </TouchableHighlight>
    )}
/>

In my view checkbox is displaying on every row, but not working.

Any one can help me. Thanks in advance.


Solution

  • You can easily do this with component separation. Please, take a look here:

    export default class ContactList extends Component {
    
        static propTypes = {
            contacts: React.PropTypes.array,
        }
    
        static defaultProps = {
            contacts: [],
        }
    
        constructor(){
            super();
            this._renderRow = this._renderRow.bind(this);
        }
    
        _renderRow(rowData,sectionID,rowID) {
            return <Contact info={ rowData } />;
        }
    
        render() {
            return (
                <ListView
                  dataSource={ this.props.contacts }
                  renderRow={ this._renderRow }  
                />
            );
        }
    }
    
    export  class ContactList extends Component {
        static propTypes = {
            info: React.PropTypes.object.isRequired,
        }
    
        constructor(){
            super();
            this.goRideDetails = this.goRideDetails.bind(this);
            this.setChecked = this.setChecked.bind(this);
        }
    
        goRideDetails() {
            //your logic here
        }
    
        setChecked() {
            this.props.info.checked = !this.props.info.checked; //will be much better to do it with redux and action creators
        }
    
        render() {
            return (
                <TouchableHighlight onPress={ this.goRideDetails }>
                    <Text style={ styles.rideHeader }>{this.props.info.name} </Text> 
                    <CheckBox checked={ this.props.info.checked } onCheckBoxPressed={ this.setChecked }  />
                </TouchableHighlight>
            );
        }
    }
    

    After that you can simply call:

    <ContactList contacts={this.state.dataSource} />
    

    in your jsx and voila.

    Important note: Do not use array functions inside your jsx code blocks.

    Important note 2: Try to start using redux or flux for storing state of your application. It will be provide much better code design.

    Hope, it will help.