Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 310
nyphur Avatar asked Aug 01 '18 14:08

nyphur


People also ask

How do you override styles in styled-components?

You can override an existing styled-components component by passing it to the styled() constructor/wrapper.

Can you style already existing components with styled-components?

If you wish to style your own existing (or any third-party) React component, then you can simply use the styled-components' styled() constructor. This works as long as the React component you're styling attaches the passed className prop (or style prop, if you're using react-native ) to the DOM element.

How do you change the style of styled component dynamically?

One way to dynamically change css properties with styled components is to insert a custom prop into your React component and access said property using the dollar sign and curly braces commonly used for template literals.

How do you overwrite React component style?

To override a style, you have two options. Either you can pass a style object, or you can pass a function that will obtain props regarding the current internal state of the component, thus enabling you to modify styles dynamically depending on the component state, such as isError or isSelected .


1 Answers

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: ...
  }
`;
like image 146
Tholle Avatar answered Sep 22 '22 11:09

Tholle