Reputation: 97
I'm rendering a Flatlist and in that I want to display a button based on if the ID of button is in my cart. How can I do so....
this is my code for button:
addBtn = (id) => {
try{
let productAdded = this.state.addedToCart;
return productAdded.map((pid) => {
if (pid == id) {
// console.log(pid);
// console.log("-----------");
console.log(id + " is added into cart");
return(
<Button
key={id}
style={{
backgroundColor: '#fff',
borderWidth: 2,
borderColor: '#2e6153',
borderStyle: 'solid',
}}
>
<Text style={{color: '#2e6153',}}>Added</Text>
</Button>
);
} else {
console.log("not added to cart");
return(
<Button
key={id}
onPress={() => {
this.saveCart(id);
}}
style={{
backgroundColor: '#2e6153',
borderWidth: 2,
borderColor: '#2e6153',
borderStyle: 'solid',
width: 80,
alignItems: 'center',
justifyContent: 'center',
}}
>
<Text>Add</Text>
</Button>
);
}
});
}catch(errors){
console.log(errors);
}
}
where id of "addBtn = (id)" is coming from renderItem of FlatList.
and this.state.addedToCart is array of my items which are in my cart. currently I added two items in cart so this.state.addedToCart = ["1015", "1016"]
and Output is: Here is the image of my output
I want to render it only once but buttons are rendering as many times as my cart size.
Upvotes: 0
Views: 54
Reputation: 422
I guess there a problem:
return productAdded.map((pid) => {
just remove it and change if statement to:
if (productAdded.includes(id)) {
so it will return only one button
Upvotes: 1