If you have n
components inside a view and you want to keep track of clicks for each of them individually, then you need to keep track of the indices for each of the components. This can be handled using a single state array.
const [coloredIndices, setColoredIndices] = useState(dates.map(item => -1))
function handleClick(index) {
setColoredIndices(indices => indices.map((value, idx) => idx === index ? -1*(value) : value))
}
return <View>
<FlatList
horizontal
showsHorizontalScrollIndicator={false}
data={dates}
keyExtractor={(_, index) => index.toString()}
renderItem={({ item, index }) => {
return (
<TouchableHighlight onPress={() => handleClick(index)} style={styles.bullet} >
<Text style={[styles.btn, coloredIndices[index] !== -1 && {color: 'green'}]}>{item.date}</Text>
</TouchableHighlight>
)
}}
/>
</View>
}
const styles = StyleSheet.create({
bullet: {
margin: 30
},
btn: {
color: "red"
}
});
The idea is as follows:
- The state is an array. There is a bijection between indices of the state and the indices of the flatlist items.
- The state is initialized with
-1
for each of the items of the data for the flatlist.
- If we click on one item, we multiply the value of the corresponding index in our state array with
-1
. This allows us to toggle between two colors.
I have made a little snack for showcasing.