Reputation: 1945
I would like to present the user with a list of items to choose from. The items are sourced from a Redux state object. It is a list of the contacts on the device.
I used a "FlatList" from React-Native and a "ListItem" from React-Native-Elements. The ListItem has a CheckBox.
For the user to check/uncheck an item in the list, he/she can click on the CheckBox or any part of the ListItem.
My 1st Attempt: As you can see in the following code, I had to duplicate part of the code to achieve this. Is there a smarter way of doing this (to avoid code duplication)?
<FlatList
keyExtractor={(item, index) => index.toString()}
data={props.contactList}
renderItem={_renderItem}
ListEmptyComponent={<Text>There are no contacts to show.</Text>}
refreshing={state.refreshing}
onRefresh={_onRefresh}
/>
const _renderItem = ({ item, index }) => {
return (
<ListItem
title={item.name}
onPress={() => {
// The following 2 statements are repeated (below)!!!
_toggleCheck(index);
props.acContactSelect(index);
}}
checkBox={{
checked: _isItemChecked(index),
checkedIcon: "check",
onPress: () => {
// The following 2 statements are repeated (above)!!!
_toggleCheck(index);
props.acContactSelect(index);
},
}}
/>
);
};
My 2nd Attempt: I tried using a function. I got the error message (Maximum update depth exceeded.)
<FlatList
.. {similar to the code above}
/>
const _renderItem = ({ item, index }) => {
return (
<ListItem
..
onPress={_onPress(index)}
checkBox={{
..
onPress: _onPress(index),
}}
/>
);
};
const _onPress = (index) => {
_toggleCheck(index);
props.acContactSelect(index);
};
Thanks for your effort and time to help...
Upvotes: 2
Views: 1349
Reputation: 3636
Please change this code
<ListItem
..
onPress={_onPress(index)}
checkBox={{
..
onPress: _onPress(index),
}}
/>
to
<ListItem
..
onPress={() =>_onPress(index)}
checkBox={{
..
onPress:() => _onPress(index),
}}
/>
onPress={_onPress(index)} will call function immediately
Upvotes: 2