Search code examples
javascriptcssreactjsstyled-components

Using props in styled-components to change styling


Edit; Solved. I am deep in a code hole and was missing a semi colon. Thanks to styled components being in back tics it doesn't check your code for error :(

I am trying to style my component as per the documentation here, but having no success. Hoping it is a simple user error, and would love some feedback. Here is my styled component file:

export const CardWrapper = styled.div`
  border: 1px solid black;
  background: ${props => (props.media ? "green" : "red")}
  width: 150px;
  height: 150px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  padding: 5px;
  margin: 15px;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.25), 0 4px 10px 0 rgba(0, 0, 0, 0.25);
  border-radius: 10px;
  &:hover {
    box-shadow: none;
  }
  &:active {
    background: ${({ theme }) => theme.colors.cardActive};
  }
`;

As you can see, the background should change based on whether or not the media prop is provided to the component. Here is my file where the component is initiated:

 <CardWrapper media>
    <H3 className="card-title">{title}</H3>
    <P className="card-subtitle mb-2 text-muted">{subtitle}</P>
    <P className="card-text">{notes}</P>
    <ButtonWrapper>
      {download ? (
        <Button onClick={buttonClick}>
           <DownloadIcon />
        </Button>
       ) : null}
    </ButtonWrapper>
 </CardWrapper>

Again, note the prop media being passed into the CardWrapper component. The result on my web page, is that the styles are all broken and nothing is working outside of the border. If I simply put background: green; or background: red; everything works again as intended. I'm pretty stumped, and hoping it is a simple user error. Thank you for your help.


Solution

  • You are missing a semicolon ; at the end of the background

    background: ${props => (props.media ? "green" : "red")};