Muhammad Umar
Muhammad Umar

Reputation: 11782

FlatList item click is not rendering this

export default class HistoryScreen extends BaseScreen {

    constructor(props){
        super(props);   
        this.state = {
            mainListData:[],
            listData:[],
            searchText:'',
        };
    }

    listRowPressed(item) {  
        this.props.navigation.navigate('Details', {
            checkin: item.data
          });
    }

    render() {
        return (
            <View style={styles.container}>

                <View style={{ flex:1, backgroundColor: '#FFF'}}>

                    <FlatList
                        data={this.state.listData}
                        renderItem={({item}) => <ListComp data={item} />}
                        keyExtractor={(item, index) => index.toString()}
                    />
                  </View>
            </View>
        );
      } 
}

const ListComp = item => (

    <TouchableOpacity onPress={() => this.listRowPressed(item)
    }>
        <View style={styles.row}>                                       
        </View>
    </TouchableOpacity>
);

I am displaying data in FlatList, however clicking on item gives me this4. listRowPressed is undefined, I tried binding the function too but didn't work. What is wrong in the code?

Upvotes: 0

Views: 259

Answers (2)

Kailash
Kailash

Reputation: 877

Try this

 <FlatList
       data={this.state.listData}
       renderItem={this.listComp}
       keyExtractor={(item, index) => index.toString()}
  /> 


listComp = ({item}) => (

    return(
         <TouchableOpacity onPress={() => this.listRowPressed(item)} >
           <View style={styles.row}> 

           </View>
         </TouchableOpacity>
         );
);

Upvotes: 0

Kishan Bharda
Kishan Bharda

Reputation: 5700

You have to pass listRowPressed in your ListComp component. Your whole code should be like this :

export default class HistoryScreen extends BaseScreen {
  constructor(props) {
    super(props);
    this.state = {
      mainListData: [],
      listData: [],
      searchText: '',
    };
  }

  listRowPressed = (item) => {
    this.props.navigation.navigate('Details', {
      checkin: item.data
    });
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={{ flex: 1, backgroundColor: '#FFF' }}>
          <FlatList
            data={this.state.listData}
            renderItem={({ item }) => <ListComp data={item} listRowPressed={this.listRowPressed} />}
            keyExtractor={(item, index) => index.toString()}
          />
        </View>
      </View>
    );
  }
}

const ListComp = (props) => (
  <TouchableOpacity 
    onPress={() => props.listRowPressed(props.item)}
  >
    <View style={styles.row}>
      {/* Do whatever with props.item here */}
    </View>
  </TouchableOpacity>
);

Also note that I have converted your method listRowPressed simple function to arrow function.

Upvotes: 2

Related Questions