Search code examples
javascripthtmlcssreactjsstyled-components

Pass props to a generic styled component in typescript


I want to make a generic component using styled components which will accept the styling properties as props. IN my case it will be a Card which will have title, avatar, name, badge and other stuff.

I want each of the element to have style prop which can be done and that something I know but how do I pass props for hover and active state stylings ?

Sample code: https://codesandbox.io/s/bold-mendel-lismke?file=/src/App.tsx

I want a different background on hover, I've tried but that's not working, how do I achieve that ?

Edit: Also I want to show a different background color when card is clicked and it will remain the same unless the user toggles


Solution

  • You're overriding styles from "styled components" with your style attribute.

    <StyledCard style={props.cardStyle} // <-- don't use this with styled-components
    

    You can use one or the other but don't mix them. When using styled components, pass the styles instead:

    <StyledCard {...props}>
    

    and define your styled-component as:

    const StyledCard = styled.div`
      background-color: ${(props: CardProps) => props.cardStyle.background};
      width: ${(props: CardProps) => props.cardStyle.width}px;
      height: ${(props: CardProps) => props.cardStyle.height}px;
      &:hover {
        background-color: ${(props: CardProps) => props.hoverBackground};
      }
    `;
    

    You can see this sandbox for reference.