when I click on an element in the flatlist, I just want to change its style. but whichever button I click, only the style of the last element changes. codes below. what do i need to do to fix it?
import { Text, View, FlatList, TouchableOpacity } from 'react-native'
import React, { useRef } from 'react'
const App = () => {
const ref = useRef()
const click = () => {
ref.current.setNativeProps({ style: { backgroundColor: 'blue' } })
}
return (
<View>
<FlatList
data={[1, 2, 3, 4, 5]}
renderItem={({ item }) =>
<TouchableOpacity onPress={() => click()} >
<View ref={ref} style={{ backgroundColor: '#eee', margin: 5, padding: 20, alignItems: 'center', borderRadius: 10 }}>
<Text>{item}</Text>
</View>
</TouchableOpacity>}
keyExtractor={(item, index) => index.toString()}
/>
</View>
)
}
export default App
2
Answers
You should use this and make the style dynamic, depending on the state value. Maybe you should store your item value in it when you pressed it.
I would suggest to drop the ref, and just control the background color with state. Also, I would recommend to combine the business logic of the items and their selection into a single state, instead of keeping that information in two separate states. E.g.