Toggle icon color upon button click using React Hooks

Viewed 1458

I'm a newbie to React. I'm trying to update the like or bookmark count to 0 and 1 upon button click. When I click on the bookmark icon, both the icons gets toggled. The behavior seems inconsistent.

ToggleIcon Component

const ToggleIcon = ({ icon, color, styledIcon, handleClick }: any) => {
  return (
    <IonIcon icon={color ? styledIcon : icon} onClick={handleClick}></IonIcon>
  );
};

Root Component

  {config.map((props, index) => (
    <ToggleIcon
      style={{ padding: "10px" }}
      handleClick={() => {
        setColor(!color);

        if (props.type === "bookmark") {
           !color && props.type === "bookmark"
           ? setBookmarkCount(bookmarkCount + 1)
           : setBookmarkCount(bookmarkCount - 1);
        }

        if (props.type === "like") {
            !color && props.type === "like"
            ? setLikeCount(likeCount + 1)
            : setLikeCount(likeCount - 1);
        }
      }}
      color={color}
      {...props}
     />
  ))}

I created a working example using CodeSandbox. Could anyone please help?

3 Answers

The root cause of your problem is using a single color state to toggle the icon color. Whenever you click on any icon it triggers a change in the color state which rerenders the entire component with that color state.

I tried using multiple states for LikeColor and BookColor and it worked like a charm.Solution Link

Solution: Codesandbox

You need to separate the color into two different states. The way you have it written, one boolean value is driving the color for both the bookmark and icon color on line 27. Just because you have a loop on line 51 does not change the fact that there is only one setColor function, which you end up using twice for both <ToggleIcon/>

I suppose by now you are better in react. Just pointing out for someone else who might need this solution. Your conditional statement inside handleClick is a bit messed up

if (props.type === "bookmark") {
           !color && props.type === "bookmark"
           ? setBookmarkCount(bookmarkCount + 1)
           : setBookmarkCount(bookmarkCount - 1);
        }

        if (props.type === "like") {
            !color && props.type === "like"
            ? setLikeCount(likeCount + 1)
            : setLikeCount(likeCount - 1);
        }
      }}
      color={color}
      {...props}

Should include an else statement instead of 2 if(s) statements see docs below https://reactjs.org/docs/conditional-rendering.html

Related