TRINA CHAUDHURI
TRINA CHAUDHURI

Reputation: 665

create an array to change color of one item at a time

I have created a like function that changes color only for a single item, and that item according to its id is liked, however when I like the first item, the id of the same is passed but all the icons are also turning to red, how do I undo that?

my like function is as follows:

onButtonPress = async(item) => {
    console.log(item)
    console.log(this.state.buttonColor,'hello')
    if(this.state.buttonColor='white'){
    try {
      const response = await fetch("some url"+item._id);
      const resJson = await response.text();
      this.setState({

        buttonColor:'red',

      }, console.log(resJson),
      console.log(this.state.buttonColor,'hi'));
    }
    catch (error) {
      console.error(error);
    }
  }

  };

I have called this function inside a flatlist as an icon, I will share the snippet of the icon below:

  <TouchableOpacity
                 onPress= {() => this.onButtonPress(item)}
                style={{
                  alignItems: 'center',

                  borderRadius: 60,
                  padding: 10,
                }}>
                <Icon
                  name="heart"
                  size={30}
                  color={this.state.buttonColor}

                />
              </TouchableOpacity>

Do, tell me if you require anything else, and let me know how to do it?

Upvotes: 0

Views: 631

Answers (3)

Rishav Kumar
Rishav Kumar

Reputation: 5450

It will apply to all other because you are not manipulating by ID's.

Try doing that by ID's or index. Flatlist render func provides you index to do so.

Upvotes: 0

Palash Kanti Bachar
Palash Kanti Bachar

Reputation: 616

Declare new state name ItemId

Assign the item into ItemId state which comes from this.onButtonPress(item) method Since every icon has unique Id so

Code looks like:

             <Icon
                  name="heart"
                  size={30}
                  color={this.stateItemId==IconId?.this.state.buttonColor:'White'}    
                />

Upvotes: 2

Alexander
Alexander

Reputation: 1380

You need store in state element's id, which have active state (red color).

onButtonPress = async(item) => {
    if(!this.state.likedItemIds.includes(item._id)){
       try {
         const response = await fetch("some url"+item._id);
         const resJson = await response.text();
         this.setState(prevState => ({
           likedItemIds: [...prevState.likedItemIds, item._id]
         }))
       }
       catch (error) {
         console.error(error);
       }
    }
};

<TouchableOpacity
 onPress= {() => this.onButtonPress(item)}
  style={{
    alignItems: 'center',
    borderRadius: 60,
    padding: 10,
  }}>
  <Icon
    name="heart"
    size={30}
    color={state.likedItemIds.includes(item._id) ? "red" : "white"}
  />
</TouchableOpacity>

Upvotes: 1

Related Questions