'How do I style a component that has `styled-components` nested in it?
I am new to styled-components. I'm trying to set styles for MyComponent to apply to styled-component.
export const Relative = styled.div`
position: relative;
`
export const Container = ({ children }) => {
return <Relative>
<AnotherComponent/>
{children}
</Relative>
}
export const MyComponent = () => <Container>/* */</Container>
How can I use styled-components to style a Container inside MyComponent without editing MyComponent?
Solution 1:[1]
When you're using styled(YourComponent), assuming YourComponent is a normal Component and not already a styled-component, this will automatically provide the className property to the component. You simple need to put that somewhere.
export const Relative = styled.div`
position: relative;
`
export const Container = ({ children }) => {
return (
<Relative>
<AnotherComponent/>
{children}
</Relative>
)
}
export const MyComponent = ({ className, children }) => {
return (
<div className={className}>
<Container>
{children}
</Container>
</div>
)
}
export const CustomMyComponent = styled(MyComponent)`
// Styles inside here will be applied to the root element of MyComponent
`;
Solution 2:[2]
You will need to wrap Container into another, like:
const MyComponentContainer = styled(Container)`
...custom styles
`
This could also help: Styling any component
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dharman |
| Solution 2 | Peter Mortensen |
