I have a project in Expo React Native where I use the map function to render elements with data. One of the elements is a photo that needs to be displayed only when the button is pressed.
I tried this but it shows and hides all the photos.
const [showPhoto, setShowPhoto] = useState(false);
//...
{readings.map(
(
{
metersID,
id,
date,
volume,
type,
},
i
) => { return (
//...some elements before this
<TouchableOpacity onPress={() => setShowPhoto(!showPhoto)}>
<FontAwesome name="photo" size={40} color="black" />
</TouchableOpacity>
{showPhoto ? (
<ImageViewer
placeholderImageSource=""
selectedImage={readings[i].photo}
/>
) : null}
//...some elements after this
2
Answers
You should create an array of booleans to track the visibility of each photo individually. Here’s how you can modify your code:
To show and hide only the specific photo related to the button pressed, you need to track the visibility of each individual photo separately. One approach is to modify your data structure to include a "showPhoto" property for each reading. Here’s how you can achieve that:
By tracking the "showPhoto" property for each reading separately, you can control the visibility of individual photos based on the button press. Each reading in the "readings" array will have its own "showPhoto" property to determine whether the photo should be displayed or not.