Reputation: 1478
I'm trying to find a way to override a styled component with styled-components like this:
Let's say I have a reusable component Wrapper:
class Wrapper extends Component {
...
render() {
const Wrap = styled.div`
padding: 5px;
background-color: green;
`;
return (
<Wrap>
{children}
</Wrap>
)
}
}
export default Wrapper
And then I have Component B that imports Wrapper but should extend the styles like this: myNewWrap uses Wrapper
import Wrapper from './Wrapper'
class B extends Component {
...
render() {
const myNewWrap = styled(Wrapper)`
background-color: red;
`;
return (
<myNewWrap>
Some awesome text
</myNewWrap>
)
}
}
Result should be that Some awesome text has padding from Wrapper but background-color from own component. But what I get is only the styles from Wrapper.
Upvotes: 1
Views: 16033
Reputation: 492
It's not perfect, but try passing your desired styles from a wrapping parent component
import Wrapper from './Wrapper'
class B extends Component {
...
render() {
const ParentOfWrapper = styled.div`
> div {
background-color: red;
}
`;
return (
<ParentOfWrapper>
<Wrapper>
Some awesome text
</Wrapper>
</ParentOfWrapper>
)
}
}
Upvotes: 0
Reputation: 6349
You can increase the specificity by adding &
multiple times (which gets replaced by the class name):
const NewWrap = styled(Wrapper)`
&& {
/* overriding styles here */
}
`
Or for certain cases use !important
.
Upvotes: -1
Reputation: 39
you override the styled component simply by passing a className to the styled component and do styling with reference to that class
<myNewWrap className="my-wrap">
Upvotes: 0
Reputation: 46
Have you considered using extend
from Styled-Components? Styled
generates new component styles with a new class whereas extend
is meant to use base styling from another Styled component, but then tweak or add additional styles.
Additionally, their docs explain when you should you use styled()
(see section "When should I use styled()
?")
when to use styled
Upvotes: 2