Reputation: 941
I have this component :
import React, { Component } from "react";
import { Text, View, Image, TouchableOpacity } from "react-native";
import { styles } from "./styles";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { getAccounts } from "../../redux/user/selectors";
const UserMenuAccount = ({ active, account, balance }) => (
<View style={styles.accountContainer}>
<Image
source={require("../../../assets/Usermenu/check.png")}
style={[styles.icon, { opacity: active ? 1 : 0 }]}
/>
<Text style={styles.text}>{account}</Text>
<Text style={[styles.text, { opacity: 0.5 }]}>{balance} ETH</Text>
</View>
);
class UserMenuAccounts extends Component {
state = {
userAccounts: [],
};
updateData = index => {
const {userAccounts} = this.state
const { GetAccounts } = this.props;
const data =[...GetAccounts]
data[index].isActive = data[index].isActive ? false : true
this.setState({userAccounts:data})
}
render() {
const { userAccounts } = this.state;
const { GetAccounts } = this.props;
return (
<View>
<Text style={{ opacity: 0.5, fontSize: 16, fontWeight: "bold" }}>
Click to switch
</Text>
{userAccounts.map((users, index) => {
return (
<TouchableOpacity onPress={()=>this.updateData(index)}>
<UserMenuAccount
account={`${users}`}
balance={0}
active={active.isActive || false}
key={index}
/>
</TouchableOpacity>
);
})}
</View>
);
}
}
const mapStateToProps = createStructuredSelector({
GetAccounts: getAccounts,
});
export default connect(mapStateToProps, null)(UserMenuAccounts)
;
The problem is I'm trying to setState active to only one UserMenuAccout but it sets active for all of them , could you please suggest me the way I can fix this ? thanks in advance , I'm grabbing accounts from redux store and mapping them as shown in the code
Upvotes: 1
Views: 106
Reputation: 6967
Try this might help
class UserMenuAccounts extends Component {
constructor(props){
this.state = {
userAccounts: props.GetAccounts,
};
}
updateData(index){
const data = […this.state.userAccounts];
data[index].isActive = data[index].isActive? false: true;
this.setState({userAccounts: data};
}
render() {
const { userAccounts } = this.state;
return (
<View>
<Text style={{ opacity: 0.5, fontSize: 16, fontWeight: "bold" }}>
Click to switch
</Text>
{userAccounts.map((users, index) => {
return (
<TouchableOpacity onPress={()=> this.updateData(index)}>
<UserMenuAccount
account={`${users}`}
balance={0}
active={users.isActive || false}
key={index}
/>
</TouchableOpacity>
);
})}
</View>
);
}
}
Upvotes: 2