When using styled-components
, we have the ability to add contextual styles utilizing the component selector pattern. But how can we target specific parent variants to style a child component contextually? In this scenario, we have three components - Child
, NoteWrapper
, and Note
.
const Child = styled.div<{ editing?: boolean }>`
${props => props.editing && css`some styles`}
`
const NoteWrapper = styled.div<{ compact?: boolean }>`
${props => props.compact && css`some styles`}
`
const Note = styled.input`
/* How can I style this when Child is editing and NoteWrapper is compact */
`
const App = () => {
return (
<Child editing>
<NoteWrapper compact>
<Note/>
</NoteWrapper>
</Child>
)
}
`
In traditional CSS, we could achieve something similar to the following:
.child.editing .note-wrapper.compact .note {
/* Contextual styles would go here */
}
While it's possible to easily pass the editing
and compact
variables to the Note
component, doing so becomes cumbersome with highly nested components.
So, my query is: how do I apply styles to Note
when Child
is in an editing
state and NoteWrapper
is compact
within the styled-components
selector pattern?
I'm not sure if there is a built-in way to accomplish this in styled-components
. Is there?
const Note = styled.input`
${Child.editingClass} ${NoteWrapper.compactClass} & {
/* Insert contextual styles here */
}
`