I have a question about styled components and what happens when a styled component is referenced in another styled component.
I know the official docs with the Link example, but I do not understand what exactly happens when a styled component is referenced.
So my question: in the following example - do the references ${A}, ${B} pass their styling to the wrapper? or only referencing to it, so change specific attributes.
How is this handled under the hood?
e.g.:
const A = styled.div`
background-color: red;
margin-top: 10px;
`
const B = styled.div`
background-color: blue;
`
const Wrapper = styled.div`
${A}, ${B} {
background-color: green;
}
`
export const NiceComponent: React.FC = () => {
return (
<Wrapper>
<A />
<B />
</Wrapper >
);
Referencing other styled components (in your example A and B) as interpolation within the pseudo-SCSS string template of a styled component (here Wrapper) is the equivalent of using their (automatically assigned) class name within your selector.
This way, you can either refer to an ancestor (as done in the docs), or target children (as in your example).
As such, this technique does not "pass styling"; to do so, you would style another styled component, like an inheritance (e.g. you could do const Child = styled(A))
In your example, styled-components will assign a class name to each component; let's say "scAAA" to component A, and "scBBB" to B. Then this code:
const Wrapper = styled.div`
${A}, ${B} {
background-color: green;
}
`
...translates into:
const Wrapper = styled.div`
.scAAA, .scBBB {
background-color: green;
}
`
So what it does is to define a new background color to all A and B components which are children of Wrapper.
But if you use them outside a Wrapper, they will have their initial styles only.