Reputation: 11
I am repeating the images and when I am click on an individual image then that single image should be clicked not all images and need to display some info after clicking on image. Please help me with this.
<TouchableHighlight
onPress={this.callFunc.bind(this)}
underlayColor="white">
<View>
{!this.state.isModalVisible && (
<Image source={require("./assets/characters/2.png")} style={styles.iconSize} />
)}
{this.state.isModalVisible && (
<View>
<Text style={{ color: "#fff" }}>You Won</Text>
<Text style={{ textAlign: "center", color: "#fff" }}>
{amt}
</Text>
</View>
)}
</View>
</TouchableHighlight>
callFunc() code:
callFunc() {
if (this.isModalVisible) {
this.setState({ isModalVisible: false });
} else {
this.setState({ isModalVisible: true });
}
}
let Blocks = [];
for (let i = 0; i <= this.state.count; i++) {
let item = imageCharacters[i];
let amt = amount[i];
Blocks.push(
<View key={i} style={styles.card}>
<TouchableHighlight onPress={this.callFunc.bind(this)} underlayColor="white">
<View> {
!this.state.isModalVisible && ( <Image source={require("./assets/characters/2.png")} style={styles.iconSize} /> )
}
Upvotes: 1
Views: 313
Reputation: 15041
You mentioned repeating images, that means that images are in an array, but your isModalVisible is a single property in the state... so when you toggle the isModalVisible property, it gets toggled for all the images...
What you need is to have the isModalVisible property against each image in the array.
relevant JS:
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
class App extends Component {
constructor() {
super();
this.state = {
name: 'React',
imgs: [
{ img: 'https://www.akberiqbal.com/Jumbo.jpg', info: 'this was a large image', display: false },
{ img: 'https://www.akberiqbal.com/JumboMob.jpg', info: 'this was a small image', display: false }
]
};
}
inFunc(passedKey) {
this.setState({ name: 'Akber' });
var someArray = [...this.state.imgs];
(someArray[passedKey].display == true) ? someArray[passedKey].display = false : someArray[passedKey].display = true;
console.log(someArray);
this.setState({ imgs: someArray });
console.log(this.state);
//this.setState({ this.state.imgs[passedKey].display: true })
}
render() {
var myImages = this.state.imgs.map((obj, index) => {
if (obj.display) {
return (
<div className='imgDiv'> <img key={index} src={obj.img} alt='nice' onClick={this.inFunc.bind(this, index)} />
INFORMATION:
</div>
)
} else {
return (
<div className='imgDiv'> <img key={index} src={obj.img} alt='nice' onClick={this.inFunc.bind(this, index)} />
INFORMATION: {obj.info} <br />
</div>
)
};
}
)
return (
<div>
<Hello name={this.state.name} />
<p>
Start editing to see some magic happen :)
</p>
{myImages}
</div >
);
}
}
render(<App />, document.getElementById('root'));
working stackblitz here
Upvotes: 1
Reputation: 6967
This might help
onPress={() => this.callFunc(i)}>
callFunc(i) {
...
}
Upvotes: 1