I have an array of images which I am able to display using flatlist. I wanted a feature where when you click on an image, it should be displayed in a separate view.
Below is my code snippet:
const [selectedImage, setSelectedImage] = useState(joy);
const [imageSet, setImageSet] = useState([joy,anger,concern,depression]);
return (
<SafeAreaView>
<View style={{width: 100, height: 400}}>
<Image style={{height: 50, width: 50}} source={selectedImage} />
</View>
<FlatList
horizontal={true}
showsHorizontalScrollIndicator={false}
data={imageSet}
renderItem={({item, index}) => (
<View>
<TouchableOpacity
onPress={(item) => {
setSelectedImage(item); // trying to select the image here
}}>
<Image
source={item}
key={index}
style={{
width: 60,
height: 60,
resizeMode: 'contain',
}}
/>
</TouchableOpacity>
</View>
)}
/>
</SafeAreaView>
);
But the images are not getting displayed when clicked on it. I am not able to figure out what the issue is. Please help.
The problem I see your code is that you are passing item to setSelectedImage from the TouchableOpacity onPress which is undefined. Thats why image is not getting set into your state.
Try this:
Before:
<TouchableOpacity
onPress={(item) => { <--- Remove this item!!
setSelectedImage(item)}}>
After:
<TouchableOpacity
onPress={() => {
setSelectedImage(item)}}>