Abdul Wahab
Abdul Wahab

Reputation: 185

CheckBox are not working in ListItem rendered with Flatlist

I am using ListItems with checkbox. Every Item in the list contain the checkBox. I am not able to check or unCheck the checkbox and also not able to select all the checkbox in the listItems. I have made both functions with 'checkBoxTest()' and 'selectAll()' I think i am not using the setState correctly. Here is my code

import React, { Component } from 'react';
import { FlatList, StyleSheet, Text, View, Image, TouchableOpacity } from 'react-native';
import { ListItem, checkBox } from 'react-native-elements';

const list = [
  {
    name: 'PinkMan',
    avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/ladylexy/128.jpg',
    subtitle: 'Vice President'
  },
  {
    name: 'Mr White',
    avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg',
    subtitle: 'Vice Chairman'
  },
]


export default class Members extends Component {
  constructor(props) {
    super(props);
    this.state = {
      checked: false,

    }
  }
  selectAll(){
    this.setState({checked: !this.state.checked})
  }

  checkBoxTest() { 
    this.setState({checked: !this.state.checked})
  } 

  keyExtractor = (item, index) => index.toString()
  renderItem = ({ item }) => (
    <ListItem
      title={item.name}
      subtitle={item.subtitle}
      leftAvatar={{
        source: item.avatar_url && { uri: item.avatar_url },
        title: item.name[0]
      }}
      checkBox={{
        checkedColor: '#744DD2',
        uncheckedColor: 'grey',
        onPress: this.checkBoxTest,
        checked: this.state.checked,
      }}
      bottomDivider
    />
  )

  render() {
    return(
      <>
        <View style={{ bottom: 60 }}>
          <FlatList
            keyExtractor={this.keyExtractor}
            data={list}
            renderItem={this.renderItem}
          />
        </View>
        <View>
          <TouchableOpacity onPress={this.selectAll} >
            <Text style={styles.textStyle}>Select All</Text>
          </TouchableOpacity>
        </View>
      </> 
    );
  }
}

Upvotes: 0

Views: 665

Answers (2)

Abhishek Ghosh
Abhishek Ghosh

Reputation: 2706

Try passing extraData={this.state} to your FlatList component.

https://facebook.github.io/react-native/docs/flatlist#extradata

Edit:

You might want to just pass extraData={this.state.checked} instead. Your FlatList should only re-render when the checked state changes. Pass other props as needed.

Upvotes: 1

ThinkAndCode
ThinkAndCode

Reputation: 1667

seems like you forgot to bind this.selectAll() and checkBoxTest()

If you wanna pass a function to onPress(), First you need to bind it in constructor.

this.selectAll = this.selectAll.bind(this); 
this.checkBoxTest = this.checkBoxTest.bind(this);

Place these two statements in constructor.

Upvotes: 1

Related Questions