Search code examples
reactjsstyled-components

How to change a component's color with styled-components?


I want to change a component Area's background color when move link hover on it.

import Link from "next/link";
...

export const ShowField: React.FC<ShowFieldProps> = ({ link, name }) => {
  return (
    <Link href={link}>
      <YellowLink>
        <Area backgroundColor="blue">
          <Area>
            <Name text={name} />
          </Area>
        </Area>
      </YellowLink>
    </Link>
  );
};

const YellowLink = styled.div`
  &:hover ${Area} {
    background-color: yellow;
  }
`;

Area is a self-created component. There is some errors if use it in the styled.div:

No overload matches this call.
  Overload 1 of 3, '(first: TemplateStringsArray | CSSObject | 

If use this way

const YellowLink = styled.div`
  a {
    &:hover {
      background-color: yellow;
    }
  }
`

There happens nothing on the page. How to haddle <Area backgroundColor="blue"> and change color for it?


Solution

  • Without seeing more of the code for the other components, this may not work for you. One approach you could take is styling a Link for your YellowLink component where you define the styles of that link.

    For example:

    // Create a styled link component...
    const StyledLink = styled(Link)`
      background-color: ${(props) => props.backgroundColor};
      // Add any additional styles you need for the link
    
      &:hover {
        background-color: yellow;
      }
    `;
    
    // Usage
    return (
      <StyledLink href={link} backgroundColor="blue">
        <Name text={name} />
      </StyledLink>
    );