Here are some styled components that I have:
const Box1 = styled.div`
// some styles
`;
const Box2 = styled.div`
background-color: ${({ someProp }) => someProp ? "cyan" : "magenta"};
${Box1} > & {
color: ${({ someProp }) => someProp ? "red" : "green"};
}
`;
I am using these components in the following way:
<Box2 someProp>Box2 (bg: cyan, color: black)</Box2>
<Box2>Box2 (bg: magenta, color: black)</Box2>
<Box1>
<Box2 someProp>Inner Box2 (bg: cyan, color: red)</Box2>
<Box2>Inner Box2 (bg: magenta, color: green)</Box2>
</Box1>
The HTML output is as follows:
<div class="pages__Box2-doZfs hsqqBA">Box2 (bg: cyan, color: black)</div>
<div class="pages__Box2-doZfs iQIEMM">Box2 (bg: magenta, color: black)</div>
<div class="pages__Box1-ifSjDr">
<div class="pages__Box2-doZfs hsqqBA">Inner Box2 (bg: cyan, color: red)</div>
<div class="pages__Box2-doZfs iQIEMM">Inner Box2 (bg: magenta, color: green)</div>
</div>
The expected styles output should be:
<style>
.hsqqBA {
background-color: cyan;
}
.pages__Box1-ifSjDr > .hsqqBA {
color: red;
}
.iQIEMM {
background-color: magenta;
}
.pages__Box1-ifSjDr > .iQIEMM {
color: green;
}
</style>
However, the actual styles output that I am getting is:
<style>
.hsqqBA {
background-color: cyan;
}
.pages__Box1-ifSjDr > .pages__Box2-doZfs {
color: red;
}
.iQIEMM {
background-color: magenta;
}
.pages__Box1-ifSjDr > .pages__Box2-doZfs {
color: green;
}
</style>
This is causing the third instance of Box2 to have a color of green instead of red.
My question is why does this happen and how can I resolve it?
Thank you