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?
You can override an existing styled-components component by passing it to the styled() constructor/wrapper.
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.
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.
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 .
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: ...
}
`;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With