Home > Blockchain >  Typescript React - Styled component conditional styling using prop not working
Typescript React - Styled component conditional styling using prop not working

Time:10-29

I'm trying to change the button's color when clicked using useState hook and styled component. When I click the button, the selected property changes but it won't apply the color.

Buttons:

      {toggleFilter.map((item) => {
          return (
            <FilterButton
              key={`${item.name}FilterButton`}
              $selected={item.selected}
              onClick={() => handleToggleFilter(item)}
            >
              {item.name}
            </FilterButton>
          );
        })}

Styled component:

export const FilterButton = styled.button<{ $selected: boolean }>`
  background-color: ${({ $selected }) => ($selected ? "#a144d5" : "#848485")};
  transition: 0.3s ease-in-out;
  color: white;
  padding: 0.25rem 0.5rem;
  margin: 0.5rem 0.1rem;
  border: none;
`;

Handler:

    const handleToggleFilter = (item: ToggleFilterItem) => {
      toggleFilter.forEach((i) => {
        if (i.name === item.name) {
          i.selected = !i.selected;
        }
      });
      setToggleFilter(toggleFilter);
  };

CodePudding user response:

You are mutating state, it should be treated as immutable, try:

const handleToggleFilter = (item: ToggleFilterItem) => {
  setToggleFilter(
    toggleFilter.map((i) =>
      i.name === item.name ? { ...i, selected: !i.selected } : i
    )
  );
};
  • Related