In my quest for a specific design outcome using styled components with shared selectors, I encountered the following challenge:
.styleOne, .styleTwo {
color: blue; /* shared */
}
.styleOne {
font-size: 10px;
}
.styleTwo {
font-size: 20px;
}
Here are some methods I tried:
1 - (This approach did not yield the desired result)
const shared = `color: blue;`
const StyleOne = styled.div`
font-size: 10px;
${shared}
`
const StyleTwo = styled.div`
font-size: 20px;
${shared}
`
2 -
const Shared = styled.div`
color: blue;
`
const StyleOne = styled(Shared)`
font-size: 10px;
`
const StyleTwo = styled(Shared)`
font-size: 20px;
`
3 -
const shared = css`
color: blue;
`
const StyleOne = styled.div`
font-size: 10px;
${shared}
`
const StyleTwo = styled.div`
font-size: 20px;
${shared}
`
All of the above attempts resulted in something like this:
.styleOne {
color: blue; /* duplicated */
font-size: 10px;
}
.styleTwo {
color: blue; /* duplicated */
font-size: 20px;
}
While technically the styles were shared from a code perspective, the rules themselves remained duplicated. My objective was to share the CSS rules directly.
To draw an analogy with SASS - I wanted to implement a placeholder instead of a mixin.
To provide context on why I pursued this goal, I aimed to streamline the HTML document for performance reasons. In a large application with numerous shared styles, the style block could become excessively lengthy.