i am a react native beginner and struggling with re-rendering a component despite state change, here is the omitted version of my component:
export default function HomeScreen({ navigation }) {
const { getItem } = useAsyncStorage("todo");
const [selectedItems, setSelectedItems] = useState([]);
function renderCard({ item }) {
return (
<TouchableHighlight
onLongPress={() => {
setSelectedItems((selectedItems) => [...selectedItems, item.title]);
}}
underlayColor="gray"
>
<Card
style={
selectedItems.includes(item.title)
? styles.cardSelected
: styles.cardNotSelected
}
>
<Card.Title style={styles.cardTitle}>{item.title}</Card.Title>
</Card>
</TouchableHighlight>
);
}
useEffect(() => {
const unsubscribe = navigation.addListener("focus", getTodoList);
return unsubscribe;
}, []);
return (
<View>
<FlatList
refreshing={loading}
onRefresh={getTodoList}
style={styles.list}
data={items}
renderItem={renderCard}
keyExtractor={(item) => item.id}
/>
</View>
);
}
const styles = StyleSheet.create({
cardSelected: {
backgroundColor: "#444333",
},
cardNotSelected: {
backgroundColor: "#ff2f2f",
},
});
I basically want to change background color of a Card when a card is longpressed, any help is appreciated!
2
Answers
I figured out the problem. Re-rendering was fine, background color setting was wrong.
Instead of:
I needed to use
containerStyle
to change the background of the card:Use the extraData prop. It will cause the FlatList to re render when the values provided changes