Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 141751

Toggle Color of Button Added To Favorites in React

$
0
0

I'm displaying a list of items and user has ability to add an item to their Favorites.

My issue is that I'm only capturing one favorite state, thus, on click of one button, all of the item buttons (red heart below) change color.

enter image description here

I'm trying to work through the best way to handle the toggling of a favorite item.

Here's the button code and the corresponding click handler:

<Table.Cell textAlign="center">
                    <Button
                      onClick={() => addFavorite(card, props.loggedUser)}
                      bordered
                      color={favorite ? "google plus" : "twitter"}
                      icon={favorite ? "heart" : "heart outline"}
                    />
                  </Table.Cell>

 const addFavorite = (card, user) => {
    console.log("CARD + USER ON CLICK", card, user);
    props.updateUser(card, user);
    setFavorite(!favorite);
  };

On click, i'm sending the favorite to the user's favorite array in database and this works successfully. (although I'm not handling any removal yet).

I also, set the state as shown with the setFavorite call above, however this is just tracking one universal 'favorite' state and not the favorite state for each item.

const [favorite, setFavorite] = useState("false");

What would be the best way to go about doing this. Should i be adding a state that holds all of the favorites?

I do have a store/state available called loggedUser which contains all of the user's information and favorite items. Should i be running a check against that maybe?

Thanks for any help on this.


Viewing all articles
Browse latest Browse all 141751

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>