Search code examples
javascriptreactjsstyled-components

Styled components not overriding styles from another component


I have a component that is already built out like so:

const Banner = ({ image, heading, text }) => (
  <Container>
    <Background src={image}>
      <BannerContent>
        <h1>{heading}</h1>
        <h2>{text}</h2>
      </BannerContent>
    </Background>
  </Container>
);

const BannerContent = styled.div`
  h1 {
    font-size: 24px;
  }

  h2 {
    font-size: 16px;
  }
`;

and I'm trying to override the styles of the h1 and h2 and add new styles like so in another component:

const PageBanner = styled(Banner)`
  h1 {
    font-size: 20px;
    width: ...
  }

  h2 {
    font-size: 13px;
    width: ...
  }
`;

However, none of that is happening. I'm assuming it's because it's nested in there? Am I able to override the styles? Or should I just build a similar component to it?


Solution

  • If you are styling one of your own custom components, you must make sure you use the className prop that styled components gives to the component.

    const Banner = ({ image, heading, text, className }) => (
      <Container className={className}>
        <Background src={image}>
          <BannerContent>
            <h1>{heading}</h1>
            <h2>{text}</h2>
          </BannerContent>
        </Background>
      </Container>
    );
    
    const PageBanner = styled(Banner)`
      h1 {
        font-size: 20px;
        width: ...
      }
    
      h2 {
        font-size: 13px;
        width: ...
      }
    `;