Reputation: 86
I have been working with react using css modules till now. I wanted to switch to styled components and there is one thing that confuses me. When working with css modules i have been creating many UI components as wrappers, passing props.children in between and then styling the wrapper in specific ".module.css" file. Now when i saw how styled components work, its like creating a component and styling that one element or even styling nested jsx tags. So styled components have wrapper behaviour. Does it kinda replace usage of props.children?
Upvotes: 0
Views: 1570
Reputation: 3860
No, Styled Components
do not force you not to use props.children
.
You can use a Styled Component as a wrapper and style children inside of it as you would do with a Component styled with a css.module:
I guess you are composing your React components like this:
// css.module
// styles.module.css
.container {
background-color: red;
}
.container > h2 {
color: green;
}
// Your React Component Wrapper:
const Wrapper = ({children}) => <div className={styles.container}>{children}</div>
// And you use it like this:
<Wrapper><h2>This text is green on a red background</h2></Wrapper>
You can do the same thing with Styled Components:
const Wrapper = ({ children }) => <StyledWrapper>{children}</StyledWrapper>;
const StyledWrapper = styled.div`
background-color: red;
& > h2 {
color: green;
}
`;
// And you use it like this:
<Wrapper><h2>This text is green on a red background</h2></Wrapper>
The result is the same and even the usage is the same, styled-components
do not force you to use a certain React Composition Pattern, it's up to you whether to style container and then select children inside of it, or if to individually style all the children.
They just give you some super-powers, for example you can target a Styled Component Child inside a Styled Component Parent, by simply calling the Component name, or you have the chance to use JS variables more easily into your css code, since all props passed to a Styled Component can be retrieved by the css.
Upvotes: 1