If you are a React developer and you are using styled-components as a helpful tool, then this article wrote for you!
As usual, you might create a styled-component and import it in other components then use it.
But what if you want to change some styles of your component on different pages? Or different components?
You can always use props for styled-components to change some properties. Right? Like this picture.
Another way is that export css
from styled-components and use it in the body of the component.
The css
function returns a string of passed styles. These styles are autoperfixed for cross-browser styles.
Like this picture.
But these are not enough for me! I want more extendable components.
I donโt know if you knew it, but the styled
accepts both object and string for styles.
So this example should be okay. Right?
So we conclude there are more ways of extending styles of a styled-components!
Now we can be creative and use it to extend our components and create components that can be styled in any way!
For example, we can use a specific prop
for extending our components.
And if you are using Typescript in your projects, you can control the value of that prop.
Like this picture.
In the above picture, we specified a prop named styles. Using React.CSSProperties
we can control the value to only valid CSS properties. That helps us to avoid crashing the app.
I hope this article helps you create beautiful UI components using styled-components.
I would be happy if you comment to me your opinion.
Top comments (5)
Why not to use default components' extending mechanism provided by styled-components?
Yes, you can use that in some cases.
But some times, it doesn't necessary to create another component extended from another component.
I'm not even sure, but I think it does affect your components tree and run-time too.
But if you send your customized styles as a prop, you just affected your build-time, not adding another component.
Run-time speed is completely negligible and isn't something which should be considered when working with Styled-components, although the output should be considered.
Both "regular" extending and your "styles" method will create 2 seperate CSS selectors.
everytime you're writing
${props...
a new selector is created for each of the props scenarios. just like each choice you make creates a parallel universe :)Well, if you don't want to add another SC component, you can just inline styles like in regular react component without introducing extra
styles
prop:That's another point (:
It will increase the React's run-time.
Because it will be added as inline-styles in HTML tag.
But if you pass this style props into the body of styled-component, it will be used in build-time.